您的位置:首页 > 其它

基类一定要设置虚析构函数,否则会内存泄露

2013-05-09 23:05 260 查看
关于虚函数,在多态当中,一定要将基类的析构函数设置为虚函数并将其实现,只有这样,才能够达到按对象构造的逆序来析构对象;否则,析构的时候,只会析构基类的那一部分,那么派生类那一部分就无法成功析构了。当指向派生类对象的指针被删除的时候,如果析构函数是虚函数(它应该如此),那么就会正确的操作——调用派生类的析构函数。由于派生类的析构函数会自动调用基类的析构函数,结果整个对象就会正确销毁。一般规律是,只要类中的任何一个函数是虚函数,那么析构函数也应该是虚函数。
#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没有运行子类的析构函数。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: