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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.