TransWikia.com

Call to make pair with mutex as argument fails. Cannot insert mutex onto unordered map

Stack Overflow Asked by Brian Yeh on January 11, 2021

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.

One Answer

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());

Correct answer by NathanOliver on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP