May 15, 2021 at 10:06pm May 15, 2021 at 10:06pm UTC
If do something like this:
1 2 3 4 5 6 7 8
int main()
{
std::unique_ptr<int > mInt = std::make_unique<int >();
// Move contents of mInt into mInt2
std::unique_ptr<int > mInt2 = std::move( mInt );
return 0;
}
What ends up happening to the first unique pointer,
mInt ? Does it get destroyed or is it left as a nullptr?
Thanks for taking the time!..
Last edited on May 15, 2021 at 10:06pm May 15, 2021 at 10:06pm UTC
May 15, 2021 at 10:07pm May 15, 2021 at 10:07pm UTC
In general, when you call the move assignment operator, the first object is left in an unspecified (but still destructible) state and should not be used.
However, the above is only a general rule of thumb. The standard library does make some guarantees for certain standard library classes, including unique_ptr.
See:
https://stackoverflow.com/questions/36071220/what-happens-to-unique-ptr-after-stdmove
mInt.get() is guaranteed to be null after the move assignment.
Last edited on May 15, 2021 at 10:15pm May 15, 2021 at 10:15pm UTC
May 15, 2021 at 10:29pm May 15, 2021 at 10:29pm UTC
Yes, that is legal. Maybe somebody else might have more useful "best practices" advice than me.
Last edited on May 15, 2021 at 10:30pm May 15, 2021 at 10:30pm UTC
May 15, 2021 at 11:44pm May 15, 2021 at 11:44pm UTC
Yep! It works perfectly, thank you!..