Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing std::move twice with the same unique_ptr

What would happen if I called std::move twice with the same unique_ptr ?

unique_ptr<int> foo(new int(5));
unique_ptr<int> bar = move(foo);
unique_ptr<int> baz = move(foo);

PS: No, std::unique_ptr usage is NOT the same question. Both questions are about unique_ptr, and this is the only common thing between them.

like image 826
user31264 Avatar asked Dec 23 '19 14:12

user31264


People also ask

Can two unique_ptr point to the same object?

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope. No two unique_ptr instances can manage the same object.

Can unique_ptr be moved?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

Is unique_ptr null after move?

Yes, you can compare it to nullptr after the move and it is guaranteed to compare equal. This is clearly true after calling release(). But std::move doesn't call release(). So how does the compiler know to restore the invariant of the unique_ptr?

Can I assign nullptr to unique_ptr?

It will work. unique_ptr& operator=(nullptr_t) noexcept ; Effects: reset() .


1 Answers

Moving from a unique_ptr leaves it as null. So baz will end up being null too.

like image 188
acraig5075 Avatar answered Sep 23 '22 23:09

acraig5075