有时需要把析构函数设置为虚函数虚函数

通常情况下,析构函数没必要设置为虚函数。如果把析构函数设置为虚函数,那么就需要给类建立一个虚表,引入一个指向虚表的指针,导致资源浪费。但是,在特殊情况下,我们需要把析构函数设置为虚函数,否则会造成内存泄漏。

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指向元素的类型。

所以,一般情况下不需要把析构函数设置为虚函数,当类中有需要在析构函数释放资源的情况下,需要把析构函数设置为虚函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值