您的位置:首页 > 编程语言 > C语言/C++

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

2011-12-31 14:57 281 查看
#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,肯定是会调用父类的析构函数的,就不存在问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: