c++基类不为虚析构函数的一个风险

本文探讨了C++中类的析构函数如何影响内存管理,特别是当子类继承父类时析构函数的重要性。通过实例展示了如何避免内存泄漏并正确释放资源。
#include <iostream>
using namespace std;

class Point {

public:

    //如果这里不写成虚拟的析构函数,子类就会有内存泄漏
	//virtual ~point()
	//{
	//	cout<<"point out"<<endl;
	//}

	~Point()
	{
		cout<<"point out"<<endl;
	}


};

class Cson:public Point
{
public:
	char* data;
	Cson()
	{
		data = (char*)malloc(5);
	}
	~Cson()
	{
		cout<<"cson out"<<endl;
		free(data);
		data = NULL;
	}

};


int main()
{
	Cson* son =  new(std::nothrow) Cson;
	Point* point = NULL;
	if (NULL != son)
	{
		point = son;
		delete point;
	}

	system("pause");
}

//输出结果
/*
point out
请按任意键继续. . .

*/

//子类的析构函数根本没被调用,除非父类的析构函数被声明为virtual
//当然直接delete son,肯定是会调用父类的析构函数的,就不存在问题


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值