[英]Will this “smart pointer” code leak memory?
我想知道来自Accelerated C ++ 14.1.2节的代码是否在调用fn
时导致内存泄漏:
class IntPtr {
public:
IntPtr (): p(NULL) {};
IntPtr (int *ip): p(ip) {};
IntPtr (const IntPtr& other) { p = new int(*other.p); };
IntPtr& operator= (const IntPtr&);
~IntPtr () { delete p; };
private:
int *p;
}
IntPtr& IntPtr::operator= (const IntPtr& other) {
if (&other != this) { delete p; p = new int(*other.p); }
return *this;
}
void fn () {
IntPtr a;
a = new int(9);
}
这是我认为到达行a = new int(9)
时发生的情况:
new int(9)
分配内存用于单个int
在堆(9),并返回一个指向这个存储器(一个int *
)。 int *
和适当的构造函数创建一个IntPtr
。 IntPtr::operator=
被调用,其中LHS a和上面创建的IntPtr
作为RHS。 此操作为单个int分配另一个内存块。 这个新块的地址存储在ap
。 当到达最后一个右括号时, a
被销毁,第二个内存块也随之被销毁。 我的问题是:第一块现在发生了什么? 它仍然在堆上,什么也没有指向吗? 行动2创建的IntPtr
的命运是什么?
我的问题是:第一块现在发生了什么? 它仍然在堆上,什么也没有指向吗? 行动2创建的IntPtr的命运是什么?
您可以重写此行:
a = new int(9);
如:
a = IntPtr(new int(9));
^^^^^^
编译器在分配期间创建一个临时对象,该对象将在分配期间使用。 它的析构函数将在语句的末尾被调用(在行的末尾使用分号)。
此代码看起来不错-不会发生内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.