I have many LoadLibrary
in my project, and need to call FreeLibrary
manually for each LoadLibrary
. I want to use the std::unique_ptr
with specific deleter
to make it auto release my dll resource.
This is what I am trying to define:
std::unique_ptr<HMODULE, BOOL(*)(HMODULE)> theDll(LoadLibrary("My.dll"), FreeLibrary);
But the compiler complains the type does not match. I found out it expects *HMODULE
from LoadLibrary
. That is std::unique_ptr<A>
will expect A*
as its pointer type. It looks I still need to define a new class to manage DLL resource(LoadLibrary
in constructor and FreeLibrary
in destructor).
Is is possible to make std::unique_ptr<A>
to just expect the A
as its pointer type?
Updated,
The following is pros and cons for new class and using std::unique_ptr, summarized from the answers.
Create another dll management class,
pros:
cons:
Use std::unique_ptr
with custom deleter,
pros:
unique_ptr
.move semantics
prevents DLL Module instance to be copied?cons:
unique_ptr
is complex and hard to find where error is.HMODULE
is void*
, a type-less type, may be a problem to integrate with unique_ptr?Please correct me at comment if I am wrong.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With