5

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?

Community
  • 1
  • 1
Marc
  • 16,170
  • 20
  • 76
  • 119

2 Answers2

12

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.

Useless
  • 64,155
  • 6
  • 88
  • 132
6

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.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274