【问题标题】:Call to make pair with mutex as argument fails. Cannot insert mutex onto unordered map调用与互斥锁配对作为参数失败。无法将互斥锁插入 unordered_map
【发布时间】:2020-11-11 02:02:32
【问题描述】:

下面是错误

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>

使用:

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

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

【问题讨论】:

  • 是否允许复制构造函数?

标签: c++ unordered-map stdtuple


【解决方案1】:

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

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

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

std::make_pair 尝试复制mtx,因为它是一个左值,但它不能因为std::mutex 不可复制。

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 重载和std::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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-23
    • 2010-09-16
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2017-11-21
    • 2010-12-17
    • 2012-06-05
    相关资源
    最近更新 更多