c++pointerssmart-pointersunique-ptrnoncopyable

Move an object containing a unique_ptr to vector


Just wondering if there is a way to move an object holding a unique_ptr into a vector of those objects? Example:

class A
{
public:
   std::unique_ptr<someData> ptr;
};

std::vector<A> objects;
A myObject;

//move myObject to objects???

Now, is there a way I could move myObject into objects and avoiding unique_ptr errors?


Solution

  • You'll need to do std::move:

    std::vector<A> objects;
    A myObject;
    
    objects.push_back(std::move(myObject));