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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With