Search code examples
c++c++14unordered-mapemplace

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,


Solution

  • One solution is to use std::unordered_map<>::operator[] that creates new elements using the default constuctor:

    auto& element = m["aString"]; // Creates a new element or gets an existing one.
    

    Or, if the return value is not needed:

    static_cast<void>(m["aString"]);