Is it safe to do the following?
auto pt = getUniquePtr();
while (pt) {
vector_of_objects.push_back(std::move(pt));
pt = getUniquePtr();
}
getUniquePtr
returns a unique_ptr<MyObject>
. I believe that, after moving away the object, it shouldn't matter if I reassign something else to pt
, right?
I'm not sure what you're worried about, but this should be absolutely safe. A unique pointer is unique. So once you've moved the pointer into the vector, pt
is an empty pointer that you are free to re-assign.
It is safe, the resources owned by pt
no longer belongs to 'pt' thanks to the std::move
. In my debugger that pointer would be set to the special has-been-deleted address.
In your example it might be "safer" to give pt
a tighter scope and reduce the duplicate getUniquePtr
call, but that's pretty marginal stylistic point.
while (true) {
auto pt = getUniquePtr();
if(pt == nullptr) break;
vector_of_objects.push_back(std::move(pt));
}
Yes, this is fine.
Moving from an object leaves it in a valid but unspecified state ; all the class invariants are maintained and operations act as specified.
This means that you can rely on being able to reassign, but can't make any guarantees about the current contents of the pointer.
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.