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;
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 );
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 );
This makes use of the second argument to the std::unique_ptr that specifies the deleter to use.
PS: map
s and unique_ptr
s 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.