how much does the default destructor do

蓝咒 提交于 2019-12-04 18:33:40

问题


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?


回答1:


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.




回答2:


The implicitly defined (default) destructor will call the destructor for each member. In the case of a member array, it will call the destructor for each element of the array.

Note that pointers don't have destructors; you need to manually delete them. You don't have this problem in the provided example, but it's something to be aware of.




回答3:


If your class/struct contains a pointer, and you explicitly allocate something for that pointer to refer to, then you normally need to write a matching delete in the dtor. Members that are directly embedded into the class/struct will be created and destroyed automatically.

class X { 
    int x; 
    int *y;
public:
    X() : y(new int) {}
    ~X() : { delete y; }    
};

Here X::x will be created/destroyed automatically. X::y (or, to be technically correct, what X::y points at) will not -- we allocate it in the ctor and destroy it in the dtor.




回答4:


Anything that you call new for must have a corresponding delete. If you didn't call new to create an instance of something then you don't have to call delete.




回答5:


You don't have to write a destructor. C++ class has the default destructor to delete the object after 'return 0' to recycle the memory.



来源:https://stackoverflow.com/questions/9952761/how-much-does-the-default-destructor-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!