Marc
Marc

Reputation: 16512

Does unique_ptr release cause memory leaks?

I'm confused about unique_ptr.release().

My goal is to cast a unique_ptr of a base class to a unique_ptr of a derived class.

So I found this question and the answer is

Derived *tmp = dynamic_cast<Derived*>(basePointer.get());
std::unique_ptr<Derived> derivedPointer;
if(tmp != nullptr)
{
    basePointer.release();
    derivedPointer.reset(tmp);
}

or

std::unique_ptr<Derived>
    derivedPointer(static_cast<Derived*>(basePointer.release()));

Then I was wondering what happen to the base pointer after basePointer.release();.

Based on this question, I understand that it causes a memory leak.

Am I right?

Upvotes: 5

Views: 1934

Answers (2)

Useless
Useless

Reputation: 67733

Am I right?

No.

Calling release() doesn't leak anything, it just signals that you are taking control of it.

If you leak a pointer after explicitly releasing it from a smart pointer, that's your fault.

Upvotes: 12

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

A memory leak happens when you lose track of the last pointer to a dynamically allocated object before you delete it. Since you copied the pointer to tmp first, you didn't lose track of it when you called release(). So no, there is no memory leak here.

Upvotes: 6

Related Questions