Is it possible to use std::unique_ptr to manage DLL resource?
According to this page, HMODULE is HINSTANCE, HINSTANCE is HANDLE, HANDLE is PVOID, and PVOID is void *. Which means that HMODULE is a pointer type. So the following should work:
std::unique_ptr<std::remove_pointer_t<HMODULE>, BOOL(*)(HMODULE)> theDll(LoadLibrary("My.dll"), FreeLibrary);
You need to provide a corresponding ::pointer
type for unique_ptr
, if you use it to manage a resource T
which is not referred to by T*
. Here T
is the first template argument of unique_ptr
.
If no ::pointer
type is not defined, T*
is used. In your case, it's HMODULE*
which is wrong.
struct tLibraryDeleter
{
typedef HMODULE pointer;
void operator()(HMODULE h) { FreeLibrary(h); }
};
std::unique_ptr<HMODULE, tLibraryDeleter>(::LoadLibraryA("My.dll"));
Check out here and here.