代码:
#include <iostream> using namespace std; class CBase { public: CBase() {} virtual ~CBase() { cout << "destructor of class CBase" << endl; } virtual void something() { cout << "do something in CBase" << endl; } }; class CDerive : public CBase { public: CDerive() {} ~CDerive() { cout << "destructor of class CDerive" << endl; } void something() { cout << "do something in CDerive" << endl; } }; int main() { CBase *b = new CDerive; b->something(); delete b; return 0; }
此时输出的是:
do something in CDerive
destructor of class CDerive
destructor of class CBase
如果将CBase里面的析构函数前面的virtual去掉,输出结果却为:
do something in CDerive
destructor of class CBase
可以看出来子类CDerive里面的析构函数根本就没有执行。关于这其中的玄机,暂时还没有精力去研究,不过看了两篇博客大致明白了意思:
http://blog.csdn.net/pathuang68/article/details/4156308
http://blog.csdn.net/pathuang68/article/details/4101970
感觉很多东西必须知其所以然才行,期待寒假再跟着上面的博主研究透彻《C++对象内存布局》