c++mutexunordered-mapemplace

C++: emplace to std::unordered_map value containing std::mutex


Could you, please, help me to figure out the right syntax of how to emplace into an std::unordered_map a value containing an std::mutex?

Here is an example:

#include <mutex>
#include <unordered_map>

using SubMap = std::unordered_map<int, float>;
struct MutexedSubMap{ std::mutex mutex; SubMap subMap; };
std::unordered_map<int, MutexedSubMap> m;

// The following do not work:
// m.emplace(7, MutexedSubMap{});
// m.emplace(7);
// m.emplace(7, {});

Solution

  • emplace forwards the arguments to a constructor. You can write a constructor for MutexedSubMap:

    #include <mutex>
    #include <unordered_map>
    
    using SubMap = std::unordered_map<int, float>;
    struct MutexedSubMap{ SubMap subMap; std::mutex mutex; MutexedSubMap(const SubMap& sm): subMap(sm){} };
    std::unordered_map<int, MutexedSubMap> m;
    
    int main() {
        m.emplace(7, SubMap{});
    }
    

    Note that m[7]; would have the same effect.