S.V
S.V

Reputation: 2793

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, {});

Upvotes: 0

Views: 239

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123094

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.

Upvotes: 1

Related Questions