Is it possible to transfer ownership from a void* to a unique_ptr?

Adr*_*ian 1 c++ c++11

I am currently using the dlopen functions for some plugin project.
This function handle returns a void* and then I save all the handle to a map named handles:

void* handle = dlopen(path.c_str(), RTLD_LAZY);  
handles[file] = handle;
Run Code Online (Sandbox Code Playgroud)

My goal is to pass the ownership to the map, I was thinking of a unique_ptr, but not sure if this is even possible.

If it's not possible what other alternatives do I have ?

CJC*_*ink 6

If I understand correctly you can do something like

Define a close function and an alias for the pointer type:

auto closeFunc = [](void* vp) {
  dlclose(vp);
};
using HandlePtr = std::unique_ptr<void, decltype(closeFunc)>;
std::map<std::string, HandlePtr> handles;
Run Code Online (Sandbox Code Playgroud)

and then create the handles and add to the map:

void* handle = dlopen(path.c_str(), RTLD_LAZY); 
HandlePtr ptr( handle, closeFunc );

handles[file] = std::move( ptr );
Run Code Online (Sandbox Code Playgroud)

Then closeFunc will be called when the unique ptr goes out of scope

The raw pointer can be prevented by combining the two lines above:

HandlePtr handle(dlopen(path.c_str(), RTLD_LAZY), closeFunc );
handles[file] = std::move( handle );
Run Code Online (Sandbox Code Playgroud)

This makes use of the second argument to the std::unique_ptr that specifies the deleter to use.

PS: maps and unique_ptrs don't play well as-is, you might need some emplaces or moves depending on the C++ standard you are using. Or use shared_ptr instead.