简体   繁体   中英

map of 2 unique_ptr's

I have a couple of questions about using unique_ptr in a container. 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. I'm using VS2012.

Now I'm not using unique_ptr s of int s; 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.

Can anyone explain the error, and how to fix it?

Second, is my MoveInfo() function bad practice? It could only be called once for each Stuff object, as the map member would be empty after it, yes?

unique_ptr are designed to take and keep ownership of a pointer, ie to be unique. 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. This is why you get the C2248 message.

Either return a reference to the map, or consider using shared_ptr (so that several maps can share a reference to the same pointer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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