虚析构函数

原来自己一直都记反了。

虚的析构函数是会自动调用基类的析构函数的,而非虚的析构函数只是简单的覆盖。

实验如下:

#include using namespace std; class BaseNotVirtual { public: BaseNotVirtual(){cout << "BaseNotVirtual obj create." << endl;} ~BaseNotVirtual(){cout << "BaseNotVirtual released." << endl;} }; class BaseVirtual { public: BaseVirtual(){cout << "BaseVirtual obj create." << endl;} virtual ~BaseVirtual(){cout << "BaseVirtual released." << endl;} }; class ChildNotVirtual : public BaseNotVirtual { public: ChildNotVirtual() {cout << "ChildNotVirtual obj create." << endl;} ~ChildNotVirtual(){cout << "ChildNotVirtual released." << endl;} }; class ChildVirtual : public BaseVirtual { public: ChildVirtual() {cout << "ChildVirtual obj create." << endl;} virtual ~ChildVirtual(){cout << "ChildVirtual released." << endl;} }; //当一个派生类对象通过使用一个基类指针删除,而这个基类有一个非虚的析构函数,则结果是未定义的 class ChildVirtualFromNot : public BaseNotVirtual { public: ChildVirtualFromNot() {cout << "ChildVirtualFromNot obj create." << endl;} virtual ~ChildVirtualFromNot(){cout << "ChildVirtualFromNot released." << endl;} }; int mian() { BaseNotVirtual* pChildNotVirtual = new ChildNotVirtual; BaseVirtual* pChildVirtual = new ChildVirtual; BaseNotVirtual* pChildVirtualFromNot = new ChildVirtualFromNot; delete pChildNotVirtual; delete pChildVirtual; //这里会出现问题 delete pChildVirtualFromNot; return 0; }

BaseNotVirtual obj create.
ChildNotVirtual obj create.
BaseVirtual obj create.
ChildVirtual obj create.
BaseNotVirtual obj create.
ChildVirtualFromNot obj create.
BaseNotVirtual released.
ChildVirtual released.
BaseVirtual released.

然后报错,因为最后一个析构会出现问题。

 

实践是检验真理的唯一标准!!!

你可能感兴趣的:(C++开发,class,delete)