user422005
user422005

Reputation: 2031

C++ move into container

I have a class like this:

class Object {
   ...
}

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

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

Now after I have initialized an Object instance I would like to add the instance to the container and forget about i.e. 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 object instance without any copying - is this possible? And would the implementation of Container::addObject be as simple as:

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

Upvotes: 3

Views: 1527

Answers (2)

fredoverflow
fredoverflow

Reputation: 263098

Instead of preparing the object and then move it into the container as the last step, why not create the object inside the container to begin with and the continue messing around with it?

Here is how you would do it with a std::vector directly:

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

Then you can do further initialization stuff with object which is already part of the vector.

Upvotes: 1

Nir Friedman
Nir Friedman

Reputation: 17704

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

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

Within the addObject function, object itself is actually an lvalue, you have to cast it back to an rvalue.

Upvotes: 3

Related Questions