Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_map emplace with default constructor

I have unordered_map with key value pairs of type string and aClass respectively; where aClass can not be moved(it has a mutex). I don't want it to be copy-constructed either; I think it wouldn't be wise to copy-construct a class that contains a mutex. To delay the construction of the item until its insertion to the map, I have tried to insert it to the map using emplace, therefore, the second argument must be empty:

aList.emplace("aString");

however, the previous line did not work. Any ideas how to emplace using the default constructor? I have also tried:

aList.emplace("aString", void);
aList.emplace("aString", {});
aList.emplace(std::piecewise_construct,"aString");

Thank you,

like image 951
b.g. Avatar asked Sep 11 '26 02:09

b.g.


1 Answers

If you have access to C++17, you can use try_emplace:

myMap.try_emplace("someKey");

This will default-construct a new element with the key "someKey".

Prior to C++17, you can use emplace using std::pair's std::piecewise_construct constructor and an empty tuple for the value's arguments:

myMap.emplace(std::piecewise_construct,
              std::forward_as_tuple("someKey"),
              std::tuple<>{});
like image 184
Miles Budnek Avatar answered Sep 12 '26 15:09

Miles Budnek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!