lundi 27 mai 2019

How to iterate over a map string keys with unique_ptr's as values?

This is a follow up question on this one.

I am using the dlopen and dlclose functions to load/unload a shared library. (They both return void*).
I am saving the dlopen handle inside a dictionary.
Every time an element is erased from the map, dlclose function should be called automatically.

This is what I have:

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

HandlePtr handle(dlopen(path.c_str(), RTLD_LAZY), closeFunc );
handles[nameStr] = std::move( handle );

My issue is when I want to iterate over the keys of the map (strings) and print them, it forces me to take the address:

vector<string> loadedLibraries;

for(auto& kv: handles) {
    loadedLibraries.push_back(kv.first);
}

return loadedLibraries;

Because of this it will clear my map when loadedLibraries goes out of scope.
If I don't take the reference I have a compilation error "using a deleted function".

I am kinda confuse by this. What is the proper way to retrieve the keys from the map ?

Aucun commentaire:

Enregistrer un commentaire