现在的位置: 首页 > 综合 > 正文

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

2014年02月13日 ⁄ 综合 ⁄ 共 499字 ⁄ 字号 评论关闭
#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,肯定是会调用父类的析构函数的,就不存在问题

抱歉!评论已关闭.