简体   繁体   English

这个“智能指针”代码会泄漏内存吗?

[英]Will this “smart pointer” code leak memory?

I want to know if this code, from Accelerated C++ Section 14.1.2, causes a memory leak when fn is called: 我想知道来自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);
}

Here's what I think happens when the line a = new int(9) is reached: 这是我认为到达行a = new int(9)时发生的情况:

  1. new int(9) allocates memory for a single int (9) in the heap, and returns a pointer to this memory (an int * ). new int(9)分配内存用于单个int在堆(9),并返回一个指向这个存储器(一个int * )。
  2. An IntPtr is created using the int * obtained above and the appropriate constructor. 使用上面获得的int *和适当的构造函数创建一个IntPtr
  3. IntPtr::operator= is called, with LHS a and the IntPtr created above as RHS. IntPtr::operator=被调用,其中LHS a和上面创建的IntPtr作为RHS。 This operation allocates another block of memory for a single int. 此操作为单个int分配另一个内存块。 The address of this new block is stored in ap . 这个新块的地址存储在ap

When the last closing brace is reached, a is destroyed, and the second block of memory with it. 当到达最后一个右括号时, a被销毁,第二个内存块也随之被销毁。 My question is: what by now has happened to the first block? 我的问题是:第一块现在发生了什么? Is it still on the heap, with nothing pointing to it? 它仍然在堆上,什么也没有指向吗? What's the fate of the IntPtr created in action 2? 行动2创建的IntPtr的命运是什么?

My question is: what by now has happened to the first block? 我的问题是:第一块现在发生了什么? Is it still on the heap, with nothing pointing to it? 它仍然在堆上,什么也没有指向吗? What's the fate of the IntPtr created in action 2? 行动2创建的IntPtr的命运是什么?

you can rewrite this line: 您可以重写此行:

a = new int(9);

as: 如:

a = IntPtr(new int(9));
    ^^^^^^ 

compiler creates during assignment a temporary object which will be used during assignment. 编译器在分配期间创建一个临时对象,该对象将在分配期间使用。 Its destructor will be called at the end of the statement (a semicolon at the end of the line). 它的析构函数将在语句的末尾被调用(在行的末尾使用分号)。

This code looks OK - no memory leak should happen. 此代码看起来不错-不会发生内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM