简体   繁体   English

2 unique_ptr的地图

[英]map of 2 unique_ptr's

I have a couple of questions about using unique_ptr in a container. 关于在容器中使用unique_ptr ,我有几个问题。 This is what I'm trying to do: 这就是我想要做的:

class Stuff
{
public: 
    std::map<std::unique_ptr<int>, std::unique_ptr<int> > GetInfo() {return m_mapInfo;}

    // Is this bad??
    std::map<std::unique_ptr<int>, std::unique_ptr<int> > MoveInfo() {return std::move(m_mapInfo);}

private:    
    std::map<std::unique_ptr<int>, unique_ptr<int> > m_mapInfo;
};

This does not compile. 这不会编译。 It gives me the error C2248. 它给我错误C2248。 I'm using VS2012. 我正在使用VS2012。

Now I'm not using unique_ptr s of int s; 现在,我不使用intunique_ptr they're actually unique_ptr s to abstract base classes, but I wanted to remove any issues of whether the error was down to my copy/move constructors/assignment operators. 它们实际上是抽象基类的unique_ptr ,但是我想消除任何有关错误是否归因于我的复制/移动构造函数/赋值运算符的问题。

Can anyone explain the error, and how to fix it? 任何人都可以解释该错误,以及如何解决该错误?

Second, is my MoveInfo() function bad practice? 第二,我的MoveInfo()函数是不好的做法吗? It could only be called once for each Stuff object, as the map member would be empty after it, yes? 只能为每个Stuff对象调用一次,因为map成员之后将为空,是吗?

unique_ptr are designed to take and keep ownership of a pointer, ie to be unique. unique_ptr用于获取并保持指针的所有权,即唯一。 This is why they are not copiable . 这就是为什么它们无法复制

Returning a copy to a map would mean to duplicate (copy) all its content which is not possible due to the unique_ptr. 将副本返回到地图将意味着复制(复制)其所有内容,这是由于unique_ptr不可能实现的。 This is why you get the C2248 message. 这就是为什么您收到C2248消息的原因。

Either return a reference to the map, or consider using shared_ptr (so that several maps can share a reference to the same pointer). 返回对映射的引用,或者考虑使用shared_ptr (以便多个映射可以共享对同一指针的引用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM