You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用emplace向含std::mutex的std::unordered_map插入元素?

向含std::mutex元素的std::unordered_map中用emplace插入元素的正确语法

问题核心在于std::mutex是不可拷贝、不可移动的类型,直接传递MutexedSubMap对象或临时对象会因尝试拷贝/移动mutex导致编译失败。以下是两种可行的写法:

方法1:使用std::piecewise_construct原地构造

#include <mutex>
#include <unordered_map>
#include <tuple>

using SubMap = std::unordered_map<int, float>;
struct MutexedSubMap{ std::mutex mutex; SubMap subMap; };
std::unordered_map<int, MutexedSubMap> m;

int main() {
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple(7),
              std::forward_as_tuple());
    return 0;
}

std::piecewise_construct允许分别传递键和值的构造参数,让MutexedSubMap直接在unordered_map的内存空间中默认构造,完全避免了mutex的拷贝或移动操作。

方法2:使用try_emplace(C++17及以上)

如果编译器支持C++17,try_emplace是更简洁的选择:

#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;

int main() {
    m.try_emplace(7);
    return 0;
}

try_emplace会检查键7是否存在,若不存在则原地构造对应的MutexedSubMap对象,同样不会触发mutex的拷贝或移动。

原写法失败原因

  • m.emplace(7, MutexedSubMap{}):临时MutexedSubMap对象需要被移动到容器中,但std::mutex不可移动,编译报错。
  • m.emplace(7):仅传递键参数,无法匹配emplace的构造规则来构造值类型MutexedSubMap。
  • m.emplace(7, {}):试图用初始化列表构造临时对象,同样会触发mutex的移动操作,导致编译失败。

内容的提问来源于stack exchange,提问作者S.V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:55:34