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.
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.
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.
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?
It will work. unique_ptr& operator=(nullptr_t) noexcept ; Effects: reset() .
Moving from a unique_ptr
leaves it as null. So baz
will end up being null too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With