简体   繁体   中英

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?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM