C ++ moves to container

I have a class like this:

class Object {
   ...
}

      

and a container that essentially consists of std::vector<Object>

:

class ObjectContainer {
public: 
    void addObject(Object ?? object);
    ...
private:
    std::vector<Object> vector;
}

      

Now, after I have initialized the instance Object

, I would like to add the instance to the container and forget about something like:

Container container;
{
    Object object(args...);
    // Maybe more object initialization

    container.addObject( object );
}

      

Now - if possible, I would like the container, i.e. std::vector<Object>

to "take" the current instance of an object without copying, is it possible? And the implementation Container::addObject

would be as simple as:

void Container::addObject( Object && object) {
   vector.push_back( object );
}

      

+3


source to share


2 answers


It wouldn't be that easy, you need one more thing:

void Container::addObject( Object && object) {
   vector.push_back(std::move(object));
}

      



Inside the addObject function, the object itself is an lvalue, you must return it to an rvalue.

+2


source


Instead of preparing an object and then moving it to the container as a final step, why not create an object inside the container to start from there and continue moving it?

This is how you could do it std::vector

directly:



std::vector<Object> vector;
vector.emplace_back(args...);
Object& object = vector.back();

      

You can then perform further initialization operations using object

that is already part of the vector.

+1


source







All Articles