The easy way is obviosuly
std::map<int,std::unique_ptr<something>> mymap;
auto f = mymap.find(5);
std::unique_ptr<something> myptr;
if (f == mymap.end())
mymap.insert({5, std::move(myptr)});
However, this doesn't look too efficient, as I have to find the key in the map twice. One to check if the key doesn't exist, and the insert function will also do the same.
If I simply use mymap.insert({5, std::move(myptr)});
then my unique ptr (myptr) is gone if pair.second
returns false (key already exists).
EDIT:
Apparently the answer is on C++17, with try_emplace
, and it's already available in the compiler I'm using (vs2015) and since I'm working on a personal project, I can afford to use it.