Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does unique_ptr release cause memory leaks?

Tags:

c++

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?

like image 692
Marc Avatar asked Dec 08 '16 18:12

Marc


1 Answers

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.

like image 127
Useless Avatar answered Oct 05 '22 20:10

Useless