析构函数为什么会自动再调用父类的析构函数?
来源:互联网 发布:欧美品牌男装淘宝 编辑:程序博客网 时间: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).
- 析构函数为什么会自动再调用父类的析构函数?
- 为什么会两次调用析构函数
- 设计模式中的单例模式的代码为什么析构函数会多次被调用,而构造函数只调用一次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- vector用erase删除元素时,为什么被删元素的析构函数会被调用更多次?
- 析构函数什么时候会调用?
- A::fun();这样调用后, A类的构造函数和析构函数是否会被调用?------不会!
- 为什么析构函数中不能调用虚函数
- 关于构造函数,拷贝构造函数与析构函数的自动调用的问题分析
- 为什么在实例化子类的对象的时候会调用先调用父类的构造函数
- C++析构函数的自动调用问题
- C++析构函数的自动调用问题
- C++析构函数自动调用,引发的一个bug
- 子类会自动调用父类的无参构造函数
- 《MySQL入门很简单》学习笔记(17)之第17章MySQL日志(关键词:MySQL/日志)
- 圆、矩形、线段碰撞检测
- 文章标题
- php 将debug信息写入文件的函数($_SERVER['PHP_SELF'])
- python运维_fourth_chapter(1)
- 析构函数为什么会自动再调用父类的析构函数?
- 服务器搬迁清单需要启动任务以及恢复办法
- jq serialize() 方法
- AndroidUtilCode
- 【3dsmax】动画的基本制作
- NOIP2017提高组 模拟赛13(总结)
- bzoj1072[SCOI2007]排列perm
- Angularjs系列之常用内置指令
- 【POJ】1236