0

Below is an error

std::mutex mtx;
            auto t = std::make_pair(std::string("hello"), mtx);

But the following is not?

std::mutex mtx;
            auto t = std::make_pair(std::string("hello"), 1);

My ultimate goal is to create a create an unordered map of type:

std::unordered_map<std::string, std::mutex>

Using:

mHeartBeatMutexes.insert(std::make_pair(std::string("hello"), mtx));

But my IDE is saying it's wrong and I'm not sure why.

1
  • Is it allowed to copy construct mutices?
    – Jeffrey
    Nov 11, 2020 at 2:05

1 Answer 1

2

std::mutex is not copyable or moveable. When you do

std::mutex mtx;
auto t = std::make_pair(std::string("hello"), mtx);

and

mHeartBeatMutexes.insert(std::make_pair(std::string("hello"), mtx));

std::make_pair tries to make a copy of mtx since it is an lvalue and it can't because std::mutex is not copyable.

In

std::mutex mtx;
auto t = std::make_pair(std::string("hello"), 1);

1 is an integer literal which materializes into a temporary integer that is moved (copy really as it's the same thing) and that's all good.

To put a mutex into a std::unordered_map<std::string, std::mutex> what you need to do is use the emplace function to directly create the pair inside the unordered_map leverage the std::piecewise_construct overload and std::forward_as_tuple to build the arguments for each member of the pair's constructor like

std::unordered_map<std::string, std::mutex> foo;
foo.emplace(std::piecewise_construct,
            std::forward_as_tuple("hello"),
            std::forward_as_tuple());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.