基类一定要设置虚析构函数,否则会内存泄露
2013-05-09 23:05
260 查看
关于虚函数,在多态当中,一定要将基类的析构函数设置为虚函数并将其实现,只有这样,才能够达到按对象构造的逆序来析构对象;否则,析构的时候,只会析构基类的那一部分,那么派生类那一部分就无法成功析构了。当指向派生类对象的指针被删除的时候,如果析构函数是虚函数(它应该如此),那么就会正确的操作——调用派生类的析构函数。由于派生类的析构函数会自动调用基类的析构函数,结果整个对象就会正确销毁。一般规律是,只要类中的任何一个函数是虚函数,那么析构函数也应该是虚函数。
shape destruction
round destruction
shape destruction另外特意做了一个实验,把这里的virtual去掉:
shape destruction没有运行子类的析构函数。
#include <iostream> using namespace std; class shape { public: shape(){}; virtual void draw() = 0; virtual ~shape(){cout << "shape destruction" << endl;} }; class rectangle : public shape { public: rectangle(){}; void draw() { } ~rectangle(){cout << "rectangle destruction" << endl;} }; class round : public shape { public: round(){}; void draw() { } ~round(){cout << "round destruction" << endl;} }; void main() { shape * s; s = new rectangle(); s->draw(); delete s; s = new round(); s->draw(); delete s; }运行结果:rectangle destruction
shape destruction
round destruction
shape destruction另外特意做了一个实验,把这里的virtual去掉:
virtual ~shape(){cout << "shape destruction" << endl;}运行结果:shape destruction
shape destruction没有运行子类的析构函数。
相关文章推荐
- 一定要配对的使用new和delete,否则将发生内存泄露(memory leak)
- C++ 为什么设置基类的析构函数为虚函数
- setFocus一定要写在setLayout设置的后面,否则不起作用——使用setFocusPolicy为控件设置不同的焦点策略:Tab焦点,Click焦点,Wheel焦点和没有焦点
- 关于多态里父类的析构函数造成子类内存泄露的问题
- C++的内存泄露与析构函数
- 条款14 基类的析构函数一定要定义为虚拟函数(From Effective C++)
- db_files 不要设置的太大,否则影响内存的使用
- 继承基类析构函数一定要加上virtual
- C++基类的析构函数为什么设置成虚函数
- 基类指针释放子类对象造成内存泄露
- C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数
- PostQuitMessage(0)要慎用,经常会造成MFC程序退出时内存泄露,还是尽量使用MFC基类的退出函数比较好。
- vc设置检查内存泄露的方法
- 基类析构函数设置成虚函数意义深远
- C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数
- C++ 为什么设置基类的析构函数为虚函数
- c++ 析构函数为虚函数 可以防止内存泄露
- C++ 设置基类的析构函数为虚函数
- 不要在基类析构函数中调用纯虚函数,否则运行时会报错“pure virtual method called”
- 析构函数,必须是virtual的,否则会内存泄漏