向std::map添加包含不可复制/移动对象的结构体

3

我有一个最小可复现的例子:

#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* 作为映射的键。这是因为它将是指针作为键,而不是指向的内容。 - Some programmer dude
@JoachimPileborg:这是一个MCVE。在我的真实项目中,它是std::string,而且foo要复杂得多。我想让它变得非常小。谢谢 - Peter VARGA
为了以后的参考,请在创建MCVE时不要添加可能存在的其他错误源,因为这只会让我们感到困惑。实际上,尽可能接近您实际程序的情况来创建一个MCVE。 - Some programmer dude
1个回答

3

关于什么?

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

?


1
@AlBundy 如果你在规划这个任务的时候“阅读”和“研究” std::map 的文档,你应该已经听说过它了... - Lightness Races in Orbit
@LightnessRacesinOrbit http://en.cppreference.com/w/cpp/container/map/emplace 有例子,但是 - 我首先检查了谷歌的排序 - http://www.cplusplus.com/reference/map/map/emplace/ 没有。 - Peter VARGA
4
@LightnessRacesinOrbit 我觉得没必要这样评论。 - M.M
@M.M:教人捕鱼胜过送人鱼,伙计。这是你今天做的最有帮助的事情。感谢你对这个主题的建设性贡献,尽管我不敢相信你只是为了说这句话而来(在我看来没有必要发表这样的评论)。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接