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:
- Fully controllable to customize for DLL semantic.
- Isolate the DLL related parts into a class with one responsibility.
- Easy to extend if need more functionality for DLL like exposing symbol.
cons:
- Need rebuild the RAII part what stadard auto pointer has been done.
- Has chance to make mistake in RAII part.
- Need Declare a new class.
Use std::unique_ptr
with custom deleter,
pros:
- No need to declare another a class.
- Reuse the RAII part of
unique_ptr
. - Maybe the
move semantics
prevents DLL Module instance to be copied?
cons:
- The Dll resource semantic may not fit the standard auto pointer, and error-prone?
- The template parameter in
unique_ptr
is complex and hard to find where error is. HMODULE
isvoid*
, a type-less type, may be a problem to integrate with unique_ptr?
Please correct me at comment if I am wrong.
theDll.get()
is null or not to knowIs LoadLibrary is succeeded?
. By https://mcmap.net/q/476209/-does-the-standard-behavior-for-deleters-differ-between-shared_ptr-and-unique_ptr-in-the-case-of-null-pointers, if thetheDll.get()
is null, thestd::unique_ptr
will not call deleter on pointer. So I don't worry I pass a NULL into FreeLibrary. – Viminal