由于参数失败,调用与互斥体配对。无法将互斥锁插入 unordered_map

2024-01-21

下面是一个错误

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

但下面的不是吗?

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

我的最终目标是创建一个类型的无序映射:

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

Using:

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

但我的 IDE 说这是错误的,我不知道为什么。


std::mutex不可复制或移动。当你这样做时

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尝试复制mtx因为它是一个左值并且不能因为std::mutex是不可复制的。

In

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

1是一个整数文字,它具体化为一个被移动的临时整数(实际上复制,因为它是同一件事),这一切都很好。

将互斥体放入std::unordered_map<std::string, std::mutex>你需要做的是使用 emplace 函数直接在unordered_map杠杆作用std::piecewise_construct https://en.cppreference.com/w/cpp/utility/piecewise_construct过载和std::forward_as_tuple https://en.cppreference.com/w/cpp/utility/tuple/forward_as_tuple为该对构造函数的每个成员构建参数,例如

std::unordered_map<std::string, std::mutex> foo;
foo.emplace(std::piecewise_construct,
            std::forward_as_tuple("hello"),
            std::forward_as_tuple());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

由于参数失败,调用与互斥体配对。无法将互斥锁插入 unordered_map 的相关文章

随机推荐