vendredi 24 novembre 2017

access unique_ptr elements in container

I have an unordered_map of unique_ptr elements. When I want to access the elements I have to move them and insert them back once I'm done using them.

std::unordered_map<std::string,std::unique_ptr<MyClass>>

auto myClass = std::move(Program::cache["my_class"]);
// do something with myClass...
Program::cache["my_class"] = std::move(myClass);

This seems very expensive so I thought using references

MyClass const& myClass = *Program::cache["my_class"];
or
auto myClass = *Program::cach["my_class"];

But this seems unnatural. Is this a common usage of containers and unique_ptr? If not what'd be the best practice?

Aucun commentaire:

Enregistrer un commentaire