What happens to a unique pointer type after using std::move?

May 15, 2021 at 10:06pm
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:07pm
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:17pm
Oh I understand...

mInt.get() is guaranteed to be null after the move assignment


Which means I could return the same contents back to it, right?

1
2
3
4
if( mInt.get() == nullptr )
{
    mInt = std::move( mInt2 );
}


Maybe something like that?
May 15, 2021 at 10:29pm
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 11:44pm
Yep! It works perfectly, thank you!..
May 16, 2021 at 11:04am
Note that the code would be simpler if you used auto - cuts down the typing and the chance of typo mistakes!

1
2
3
4
5
6
7
8
9
#include <memory>

int main()
{
	auto mInt {std::make_unique<int>()};

	// Move contents of mInt into mInt2
	auto mInt2 {std::move(mInt)};
}

Topic archived. No new replies allowed.