3

Let's say

class A {
  A* array;
public:
   A (){ 
    array= new A [4];
  }

  ~A (){
    delete array;
  }
}

How do we free an object if we create such an object on heap like

A* object_ptr =new A();

I'm a bit confused about freeing a pointer that points to an object containing another pointer.....

Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
GalaxyVintage
  • 656
  • 1
  • 11
  • 20

2 Answers2

8

Calling

delete object_ptr;

after

A* object_ptr =new A();

will invoke the destructor of the A pointed to by object_ptr. That means, if you fix your wrong

~A (){
  delete array;
}

to

~A (){
  delete[] array;
}

your code will be fine and the internal pointer is freed correctly.

However, you really should use std::vector instead of new[]. It will make your life a whole lot easier. If you insist on new[], read about The Rule of Three.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
5

Two things to note.

  1. When deleting arrays you should use []. For example: delete [] array;
  2. When deleting pointers the destructor of the allocated object will get called. You would call from your code: delete object_ptr; to delete your pointer.

Another important point to be aware of is what happens when you copy your object. If your object ever gets copies you will have problems where one destructor deletes the pointers out from under another object. This is why shared_ptr is a good alternative to raw pointers (see this question on how to use shared_ptr).

Community
  • 1
  • 1
Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69
  • If I assign the object_ptr to a new pointer, would it cause the same problem? – GalaxyVintage May 25 '15 at 20:16
  • Yes. If you write: `A *a = new A(); A *b = a; delete a;` then `b`'s internal `array` will be deleted as well. – Benjy Kessler May 25 '15 at 20:17
  • Hmm..also if an object is created by a method in stack with one of its fields created in the heap, does the memory in the heap get freed after? – GalaxyVintage May 25 '15 at 21:21
  • Yeah the destructor of an object on the stack will be called when the object goes out of scope. – Benjy Kessler May 25 '15 at 21:31
  • I have a program that returns`A object `, and for some reason after the method, when the object is return to another variable `A new_object`, I can still access all the fields with no trouble. And I am confused as they should be gone by then since they are created instack...unless assign operator is different when I use `A new_object = some_method()` – GalaxyVintage May 26 '15 at 00:02
  • This is because of RVO (see https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization) – Benjy Kessler Aug 09 '18 at 13:12