Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a std::unique_ptr moved into a std::vector when using push_back?

I have a question about how a std::unique_ptr is inserted into a std::vector. Imagine I have a function that produces objects as follows:

std::unique_ptr<CObject> createObjects()
{
    return std::unique_ptr<CObject> (new CObject());
}

Now in my code, I have a std::vector<std::unique_ptr<CObjects>> vec and I insert elements like so:

vec.push_back(createObjects());

Now my question is: Is the unique_ptr moved into the vector or is it copied?

like image 712
Foaly Avatar asked Dec 12 '22 09:12

Foaly


1 Answers

A unique_ptr cannot be copy-constructed or copy-assigned. In the case of a push_back into a vector, it is moved, provided it is an rvalue. To test this, you can try pushing an lvalue. This would require the unique_ptr to be copyable or assignable, and so would fail:

std::unique_ptr<CObject> p(new CObject());
std::vector<std::unique_ptr<CObject>> vec;
vec.push_back(p); // error!
vec.push_back(std::unique_ptr<CObject>(new CObject())); // OK
vec.push_back(std::move(p)); // OK
like image 199
juanchopanza Avatar answered Dec 13 '22 22:12

juanchopanza