Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting array of class objects?

It's almost common knowledge that the code below correctly frees the memory of 100 integers.

int* ip = new int[100];
delete [] ip; 

And I think even for user defined classes it works:

Node* ip = new Node[100];
delete [] ip; 
  1. In the first case, is the size of memory to be freed (400 bytes), determined at compile time? Basically, what goes on internally?

  2. In the second case, will the destructor of Node be called on each of the 100 objects?

Essentially, I have been using this syntax, but never understood what goes on internally and now I am curious.

like image 896
tanon Avatar asked May 11 '11 06:05

tanon


1 Answers

  1. No. The memory allocator invisibly keeps track of the size. The size cannot be determined at compile time, because then the allocation would not be truly dynamic and the following would not work:

size_t n;
std::cin >> n;
a = new int[n];
// do something interesting
delete[] a;
  1. Yes. To convince yourself of this fact, try

struct Foo {
    ~Foo() { std::cout << "Goodbye, cruel world.\n"; }
};

// in main
size_t n;
std::cin >> n;
Foo *a = new Foo[n];
delete[] a;
like image 166
Fred Foo Avatar answered Sep 30 '22 14:09

Fred Foo