[英]Does unique_ptr release cause memory leaks?
I'm confused about unique_ptr.release()
. 我对unique_ptr.release()
感到困惑。
My goal is to cast a unique_ptr of a base class to a unique_ptr
of a derived class. 我的目标是蒙上的unique_ptr基类的到unique_ptr
派生类的。
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();
然后我想知道basePointer.release();
之后基址指针发生了什么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 . 调用release()
不泄漏任何东西,它只是表明你正在控制它 。
If you leak a pointer after explicitly releasing it from a smart pointer, that's your fault. 如果你明确后从智能指针释放它泄漏的指针,那是你的错。
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()
. 由于您首先将指针复制到tmp
,因此在调用release()
时没有忘记它。 So no, there is no memory leak here. 所以不,这里没有内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.