虚析构的作用

来源:互联网 发布:人工智能英语作文 编辑:程序博客网 时间:2024/06/07 06:55

为什么在写类的时候,析构函数要定义为虚函数呢?

主要作用:是为了防止,在实现多态的时候在用父类的指针操作派生类对象后,在析构的时候只回收了基类的资源,没有析构派生类函数;这样造成了内存的泄漏!!

总之,用作基类的析构写作一个虚析构是一个好的习惯!!

来看一段代码示例就懂了:

#include <iostream>#include <assert.h>using namespace std;class father{public:int a ;double b;father(){cout<<"father constructor!"<<endl;}virtual ~father(){cout<<"~father !"<<endl;}virtual void show(){cout<<"father"<<endl;}};class son:public father{public:int c;void show(){cout<<"son"<<endl;}son(){cout<<"son constructor!"<<endl;}~son(){cout<<"~son !"<<endl;}};class grandson:public son{public:void show(){cout<<"grandson"<<endl;}grandson(){cout<<"grandson constructor!"<<endl;}~grandson(){cout<<"~grandson !"<<endl;}};int main(){father *p=new son;delete p;father *p1=new grandson;delete p1;system("pause");return 0;}
如果基类的father的析构函数没有被申明为虚的,其结果为:


可以看到,delete的时候只是回收了父类的资源,乜有析构派生类的资源;

但是将基类的析构函数设置为虚函数后:


我们可以看到,如果基类的析构函数是虚的,那么在执行析构函数时,程序会先执行new出来的派生类的析构函数,然后依次执行其父类的析构函数!防止了内存的泄漏!!


4 0
原创粉丝点击