【问题标题】:Adding struct containing not copyable/moveable object to std::map将包含不可复制/可移动对象的结构添加到 std::map
【发布时间】:2023-04-10 20:13:01
【问题描述】:

我有这个 MCVE:

#include <atomic>
#include <map>
#include <string>

struct foo
{
    int intValue;
    std::atomic_bool bar;

    foo( int intValue ) : intValue( intValue ) {};
};

std::map<std::string, foo> myMap;

int main()
{
    myMap.emplace( "0",  1234 );
}

它无法编译,因为std::atomic 既不可复制也不可移动。

我的问题:

如何将包含不可复制/可移动对象的类添加到std::map 容器?

【问题讨论】:

  • 你真的不应该使用const char* 作为映射的键。那是因为 pointer 才是关键,而不是它指向的东西。
  • @JoachimPileborg:这是一个MCVE。在我的实际项目中,它是std::string,而foo 要复杂得多。我想让它变得非常小。谢谢
  • 为了将来参考,在创建MCVE时,请不要添加其他可能的错误来源,因为那只会让我们感到困惑。实际上创建一个MCVE,尽可能接近你的实际程序。

标签: c++ c++11 stl


【解决方案1】:

怎么样

myMap.emplace(std::piecewise_construct,
              std::forward_as_tuple("0"),
              std::forward_as_tuple(1234));

【讨论】:

  • @AlBundy 如果您作为计划的一部分阅读研究std::map的文档,您就会听说过它任务...
  • @LightnessRacesinOrbit http://en.cppreference.com/w/cpp/container/map/emplace 有这个例子,但是 - 由于谷歌排序顺序,我首先检查了 - http://www.cplusplus.com/reference/map/map/emplace/ 不是
  • @LightnessRacesinOrbit 不需要这样的 cmets 恕我直言
  • @M.M: 教人钓鱼,伙计。这是你一整天都会做的最有帮助的事情。不过,感谢您对该线程的建设性贡献(不敢相信您来到这里只是这么说 - 不需要这样的 cmets 恕我直言)
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
相关资源
最近更新 更多