通常情况下,析构函数没必要设置为虚函数。如果把析构函数设置为虚函数,那么就需要给类建立一个虚表,引入一个指向虚表的指针,导致资源浪费。但是,在特殊情况下,我们需要把析构函数设置为虚函数,否则会造成内存泄漏。
1.出现内存泄漏的情况
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
};
~Base(){
cout<<"this is Base"<<endl;
};
};
class Derive:public Base
{
public:
Derive(){
p=new int[10];
}
~Derive(){
cout<<"this is Derive"<<endl;
}
private:
int * p;
};
int main(){
Base * a=new Derive();
delete a;
return 0;
}
在这种情况下,Derive中的析构函数没有被执行,导致Derive中申请的资源没有释放,出现内存泄漏。Base类指针指向的是Derive,因为析构函数不是虚函数,那么当我们用delete释放a的时候,导致a调用的是指针类型的析构函数,从而出现内存泄漏。
我们把代码稍微修改一下,把析构函数设置为虚函数
#include <iostream>
using namespace std;
class Base
{
public:
Base(){
};
virtual ~Base(){
cout<<"this is Base"<<endl;
};
};
class Derive:public Base
{
public:
Derive(){
p=new int[10];
}
~Derive(){
cout<<"this is Derive"<<endl;
}
private:
int * p;
};
int main(){
Base * a=new Derive();
delete a;
return 0;
}
此时,由于析构函数是虚函数,那么在delete a的时候,a调用的是a指向元素的类型。
所以,一般情况下不需要把析构函数设置为虚函数,当类中有需要在析构函数释放资源的情况下,需要把析构函数设置为虚函数。