虚析构函数

class BaseClass
{
public:
	BaseClass() {}
	~BaseClass() 
	{
		std::cout << "delete BaseClass" << std::endl;
	}
};
 
class ChildClassA : public BaseClass
{
public:
	ChildClassA() {}
	~ChildClassA() 
	{
		std::cout << "ChildClassA Delete" << std::endl;
	}
};
class ChildClassB : public ChildClassA
{
public:
	ChildClassB() {}
	~ChildClassB()
	{
		std::cout << "ChildClassB Delete" << std::endl;
	}
};
void main(){
    // 测试案例
    BaseClass *a = new ChildClassA();
	BaseClass *b = new ChildClassB();
	ChildClassA *c = new ChildClassB();
 
	delete a;
	a = nullptr;
	std::cout << std::endl;
 
	delete b;
	b = nullptr;
	std::cout << std::endl;
 
	delete c;
	c = nullptr;
}
//delete BaseClass
//
//delete BaseClass
//
//ChildClassA Delete
//delete BaseClass
class BaseClass
{
public:
	BaseClass() {}
	virtual ~BaseClass() 
	{
		std::cout << "delete BaseClass" << std::endl;
	}
};
//ChildClassA Delete
//delete BaseClass
//
//ChildClassB Delete
//delete BaseClass
//
//ChildClassB Delete
//ChildClassA Delete
//delete BaseClass

 虚析构函数:当基类指针指向子类对象的时候,需要把基类的析构函数设置成虚析构,防止内存泄露

posted @ 2022-06-16 11:10  wuyuan2011woaini  阅读(40)  评论(0编辑  收藏  举报