虚析构函数

        虚析构函数可以解决基类的指向派生类对象,并用基类的指针直接释放派生类对象的问题

        当一个类不准备作为基类使用时,使用虚析构函数并不是一个好主意。因为不作基类的情况下,这个类就没有必要定义其他虚函数,采用虚析构函数会为类增加一个虚函数表指针的长度,使得类对象占用的空间增加,还有可能降低其可移植性。如下代码所示:

#include "stdafx.h"
class Base
{
public:
	~Base()
	{
		printf("The Base Destructor is Called!\n");
	}
};

int main()
{
	int sz = sizeof(Base);
	printf("sizeof Base = %d\n",sz);
	/// 
	getchar();
	return 0;
}

 备注:对于没有成员变量的类,默认会补充一个char的长度,所以长度为1

        将其析构函数改为虚析构函数后,其长度变为了4,空间有所增加,代码如下。

#include "stdafx.h"
class Base
{
public:
	virtual ~Base()
	{
		printf("The Base Destructor is Called!\n");
	}
};

int main()
{
	int sz = sizeof(Base);
	printf("sizeof Base = %d\n",sz);
	/// 
	getchar();
	return 0;
}

         虚析构函数的典型应用代码如下:

#include "stdafx.h"

/// 
class Base
{
public:
	virtual ~Base()
	{
		printf("The Base Destructor is Called!\n");
	}
};

//
class Child:public  Base
{
public:
	 ~Child()
	{
		printf("The Child Destructor is Called!\n");
	}
};

///
class SubChild:public Child
{
public:
	~SubChild()
	{
		printf("The subChild Destructor is Called!\n");
	}
};

///
class Sub2Child:public SubChild
{
public:
	 ~Sub2Child()
	{
		printf("The Sub2Child Destructor is Called!\n");
	}
};
/// -------------------------
int main()
{
	Base  *pBase  = new Sub2Child;
	if(pBase)
	{
		delete pBase;
		pBase = NULL;
	}
	/// 
	getchar();
	return 0;
}

         只需要把基类析构函数变为虚析构函数,将子类的(可能是多级继承)对象赋给基类指针,释放基类的指针也会触发到子类的析构函数调用。结果如下:

         如果是非虚析构函数的话,将只会释放基类的指针,代码如下:

#include "stdafx.h"

/// 
class Base
{
public:
	 ~Base()
	{
		printf("The Base Destructor is Called!\n");
	}
};

//
class Child:public  Base
{
public:
	 ~Child()
	{
		printf("The Child Destructor is Called!\n");
	}
};

///
class SubChild:public Child
{
public:
	 ~SubChild()
	{
		printf("The subChild Destructor is Called!\n");
	}
};

///
class Sub2Child:public SubChild
{
public:
	  ~Sub2Child()
	{
		printf("The Sub2Child Destructor is Called!\n");
	}
};


/// -------------------------
int main()
{
	Base  *pBase  = new Sub2Child;
	if(pBase)
	{
		delete pBase;
		pBase = NULL;
	}
	/// 
	getchar();
	return 0;
}

 如果子类的析构函数为虚析构函数,那么要求其基类也应该定义虚析构函数。代码如下:

#include "stdafx.h"

/// 
class Base
{
public:
	 ~Base()
	{
		printf("The Base Destructor is Called!\n");
	}
};

//
class Child:public  Base
{
public:
	 virtual ~Child()
	{
		printf("The Child Destructor is Called!\n");
	}
};
/// 
int main()
{
	Base  *pBase  = new Child;
	if(pBase)
	{
		delete pBase;
		pBase = NULL;
	}
	/// 
	getchar();
	return 0;
}

         这种情况下,打印结果为只调用基类的虚析构函数,且还会有程序异常。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

saint198

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值