析构函数为什么会自动再调用父类的析构函数?

来源:互联网 发布:欧美品牌男装淘宝 编辑:程序博客网 时间:2024/04/30 10:25

原帖: http://bbs.csdn.net/topics/380022416

里面的讨论基本上已经给出答案了,派生类的析构函数在执行完后,会自动执行基类的析构函数,这个是编译器强制规定的,没有为什么,甚至你在析构函数里调用return都不会立即返回到调用处,而是会先按顺序把析构函数全部调用完。


以下是从stackoverflow上找到的回答,引用了RTTI,解释的也更专业一点。

https://stackoverflow.com/questions/3261694/why-base-class-destructor-virtual-is-called-when-a-derived-class-object-is-del


The Standard says

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant members,the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes. All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes. Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2). A return statement (6.6.3) in a destructor might not directly return to the caller; before transferring control to the caller, the destructors for the members and bases are called. Destructors for elements of an array are called in reverse order of their construction (see 12.6).

Also as per RAII resources need to be tied to the lifespan of suitable objects and the destructors of respective classes must be called upon to release the resources.

For example the following code leaks memory.

 struct Base {       int *p;        Base():p(new int){}       ~Base(){ delete p; } //has to be virtual }; struct Derived :Base {       int *d;       Derived():Base(),d(new int){}       ~Derived(){delete d;} }; int main() {     Base *base=new Derived();     //do something     delete base;   //Oops!! ~Base() gets called(=>Memory Leak).

阅读全文
0 0
原创粉丝点击