小谈虚析构函数 一、可以先看一下下面的例子: #include <iostream> using namespace std; class Mother { public: //最主要的区别就是在析构函数前加没加virtual;分别观察结果(A和B两种情况) ~Mother(){ cout << "~Mother" << endl;} //virtual ~Mother(){cout << "~Mother()" << endl;}// }; class Son :public Mother { public: ~Son(){cout << "~Son()" << endl;} }; class Grandson:public Son { public : ~Grandson() {cout << "~Grandson()" << endl;} }; int main() { Mother *one = new Son ; Mother *two = new Grandson; Son *three = new Grandson; Grandson four; delete one; delete two; delete three; system("pause"); return 0; }
A:当基类Mother的析构函数不是virtual 输出情况为: ~Mother() ~Mother() ~Son() ~Mother() ~Grandson() ~Son() ~Mother() 第一行是delete one输出的结果;第二行是delete two的输出结果;第三.四行是delete three的输出结果; 第5~7行是Grandson four的虚构函数 B:当基类Mother的析构函数是virtual 输出情况为: ~Son() ~Mother() ~Grandson() ~Son() ~Mother() ~Grandson() ~Son() ~Mother() ~Grandson() ~Son() ~Mother() 明显发现输出结果要安全得多,每一个的析构函数都调用了.这对程序的健壮性和安全性是非常重要的. 
|