1. 程式人生 > >解構函式為什麼會自動再呼叫父類的解構函式?

解構函式為什麼會自動再呼叫父類的解構函式?

原帖: 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.

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