0

I am unaware of a good way to check this myself, so I am asking here. I am pretty new to smart pointers so my question is: In this code example, will all handlers be automatically closed? Is there something else that should be done?

#include <stdio.h>
#include <windows.h>
#include <fileapi.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <memory>

struct Deleter
{
    void operator()(HANDLE* h)
    {
        CloseHandle(*h);
    }
};

void Close(HANDLE* handle)
{
    CloseHandle(*handle);
}

void helper()
{
    std::wstring str = L"Project2.exe 30 30";
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    CreateProcess(NULL, str.data(), nullptr, nullptr, false, NORMAL_PRIORITY_CLASS, nullptr, nullptr, &si, &pi);
    STARTUPINFO li = { sizeof(si) };
    PROCESS_INFORMATION ki;
    CreateProcess(NULL, str.data(), nullptr, nullptr, false, NORMAL_PRIORITY_CLASS, nullptr, nullptr, &li, &ki);

    std::unique_ptr<HANDLE, Deleter> xx = std::unique_ptr<HANDLE, Deleter>(&pi.hProcess);
    std::unique_ptr<HANDLE, Deleter> yy(&pi.hThread);
    std::shared_ptr<HANDLE> zz(&ki.hProcess, Close);
    std::shared_ptr<HANDLE> ww(&ki.hThread, Close);
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    helper();
}

Unfortunately, using CHandle is not possible for me.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 5
    Not sure why you need the level of indirection. `HANDLE` is typedef'd as `void*` so you can use `std::unique_ptr` and have `Deleter` take a `HANDLE` rather than a pointer to a `HANDLE`. – Jonathan Potter Dec 04 '22 at 19:26
  • 2
    You can check it yourself by stepping through the code and seeing whether the handles get closed. Set a breakpoint on your custom `operator()(HANDLE *)`. – Raymond Chen Dec 04 '22 at 19:38
  • I have a small example here https://codereview.stackexchange.com/q/260165/183642 – Aykhan Hagverdili Dec 04 '22 at 19:57
  • Why re-invent something that already exists? There's a very simply ATL header that ships with Visual Studio that has the [CHandle](https://learn.microsoft.com/en-us/cpp/atl/reference/chandle-class?view=msvc-170) class. Its destructor will close the handle attached to it. All you need to do is `#include ` – selbie Dec 04 '22 at 20:06
  • 2
    Use the WIL's [RAII resource wrappers](https://github.com/Microsoft/wil/wiki/RAII-resource-wrappers). – IInspectable Dec 04 '22 at 22:03

0 Answers0