虚析构函数

虚析构函数就是为了当删除一个派生类对象的时候,派生类的析构函数被调用。。。

vs2013编译的一个程序:

头文件:default.h

#include <iostream>
#include <cstring>
using namespace std;

class CBase
{
public:
	CBase();
	virtual ~CBase();
};

class CDerived : public CBase
{
public:
	CDerived(char *str);
	~CDerived();
private:
	char *name;
};


函数实现:

function.cpp

#include "default.h"

CBase::CBase()
{
	cout << "构造函数CBase被调用!!" << endl;
}

CBase::~CBase()
{
	cout << "析构函数CBase被调用!!" << endl;
}

CDerived::CDerived(char *str)
{
	name = new char[strlen(str) + 1];
	strcpy_s(name,strlen(str)+1 ,str);  //这里的strcpy_s一定要是三个参数
	cout << "构造函数CDerived被调用!!" << endl;
}

CDerived::~CDerived()
{
	cout << "析构函数CDerived被调用!!" << endl;
	if (name)
	{
		delete []name;
		name = NULL;
	}
		
}

主函数:

main.cpp

#include "default.h"

int main(int argc, char* argv [])
{
	CDerived derived("ding");
	CBase *p1 = &derived;
	cout << "----------强制析构----------------" << endl;
	p1->~CBase();
	cout << "----------new CDerived------------" << endl;
	CBase *p2 = new CDerived("zheng");
	delete p2;
	cout << "----------delete CDerived---------" << endl;
	return 0;
}

执行代码的结果:

当我们把

class CBase
{
public:
	CBase();
	virtual ~CBase();
};

修改为

class CBase
{
public:
	CBase();
	~CBase();
};

把virtual去掉之后编译的结果:

明显可以看出不用虚析构函数之后,当我们删除派生类CDerived的对象p2的时候,它的析构函数没有被调用!

这里就会造成内存泄露。

而且也不是所有的类都要虚析构函数,一般只用于基类。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值