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,肯定是会调用父类的析构函数的,就不存在问题
相关文章推荐
- 为多态基类声明一个虚析构函数(Effective C++_7)
- C++学习笔记-----存在多态调用时,为基类定义虚析构函数
- 基类为何需要有一个虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- 一个类做为基类时,如果有析构函数,则析构函数必须是虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- [C++] 基类一定要定义虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- C++ 虚析构函数-(一个带有虚函数功能的类,则它需要一个虚析构函数)
- C++中基类的析构函数为什么要用virtual虚析构函数
- C++中基类和派生类的一个应用
- 读书笔记 effective c++ Item 7 在多态基类中将析构函数声明为虚析构函数
- c++只在基类中用虚析构函数的原因
- c++只在基类中用虚析构函数的原因
- C++中基类的析构函数为什么要用virtual虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- C++中基类的析构函数为什么要用virtual虚析构函数
- c++子类调用基类方法的一个例子
- 用c++建立一个形状类Shape作为基类,派生出圆类Circle和矩形类Rectangle,求出面积并获取相关信息。
- C++中基类的析构函数为什么要用virtual虚析构函数