tanon
tanon

Reputation: 105

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.

Upvotes: 5

Views: 4302

Answers (1)

Fred Foo
Fred Foo

Reputation: 363858

  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;

Upvotes: 7

Related Questions