Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how much does the default destructor do

Does the default destructor in C++ classes automatically delete members that are not explicitly allocated in code? For example:

class C {
  public:
    C() {}
    int arr[100];
};

int main(void) {
  C* myC = new C();
  delete myC;
  return 0;
}

Does delete myC deallocate myC's arr automatically? Or do I need to write C's destructor to do this explicitly?

like image 601
Robz Avatar asked Mar 31 '12 03:03

Robz


1 Answers

The constructor (in the absence of any ctor-initializer-list) calls the default constructor for each subobject.

Since you have no base classes and your member variables are primitive types, it will do nothing at all.

Same with the destructor. Yours is implicitly compiler-generated since you haven't declared one, and it will call the destructor for each subobject. Again that's trivial because your only subobject is an aggregate of primitives.

Now, all memory of the class will be freed when you delete it. Since the array is embedded inside the class, it's part of the same memory region and will be freed at the same time.

like image 177
Ben Voigt Avatar answered Sep 20 '22 05:09

Ben Voigt