简体   繁体   中英

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:

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:

  1. new int(9) allocates memory for a single int (9) in the heap, and returns a pointer to this memory (an int * ).
  2. An IntPtr is created using the int * obtained above and the appropriate constructor.
  3. IntPtr::operator= is called, with LHS a and the IntPtr created above as RHS. This operation allocates another block of memory for a single int. The address of this new block is stored in ap .

When the last closing brace is reached, a is destroyed, and the second block of memory with it. 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?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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