3

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 );
}
2
  • 1
    try container.addObject( std::move(object) );, keeping the definition as addObject(Object && object) Commented Jul 30, 2015 at 22:29
  • I assume Object is cheap to move otherwise you won't get much benefit from this. Commented Jul 31, 2015 at 1:59

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Yes - I might actually do it this way; I know learned about vector.emplace_back()- that was new to me. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.