Siyavash
Siyavash

Reputation: 980

release() in unique_ptr C++

I have been working with unique_ptr for few days now and I have a question about the release method of unique_ptr. I know that release returns the "Pointer to the managed object or nullptr if there was no managed object".

Lets say we have three unique_ptr variables:

unique_ptr< Node > left(Node);
unique_ptr< Node > right(Node);
unique_ptr< Node > middle(Node);

Now I want to change the pointers inside them:

middle.release();
right.release();
left.release();

middle.reset(right.get());
right.reset(left.get());
left.reset(middle.get());

Would this cause any memory leak? Is it better to store the values returned by release() and then use them or is it fine this way?

Upvotes: 0

Views: 263

Answers (2)

Daniel Trugman
Daniel Trugman

Reputation: 8501

According to cppreference.com release() does the following:

Releases the ownership of the managed object if any. get() returns nullptr after the call.

So, once you released all your objects, you have lost your pointers! And since they were owned by the unique_ptr-s, they are now in the wild!

Instead, use swap to achieve the same goal carefully:

right.swap(middle); // middle = right, right = middle
right.swap(left); // left = right = (old) middle, right = left

Upvotes: 2

You are leaking! release nullifies the pointer. You lose the original object pointers.

What you want is accomplished by simply swapping twice:

middle.swap(right);
right.swap(left);

Upvotes: 1

Related Questions