c++ 虚析构函数[避免内存泄漏]

时间:2021-10-08 19:53:18

c++  虚析构函数:

虚析构函数
(1)虚析构函数即:定义声明析构函数前加virtual 修饰, 如果将基类的析构函数声明为虚析构函数时,
由该基类所派生的所有派生类的析构函数也都自动成为虚析构函数。

(2)基类指针pbase 指向用new动态创建的派生类对象child时,用“delete pbase;”删除对象分两种情况:
第一,如果基类中的析构函数为虚析构函数,则会先删除派生类对象,再删除基类对象
第二,如果基类中的析构函数为非虚析构函数,则只会删除基类对象,不会删除派生类对象,这样便出现了内存泄漏了

#include <iostream>
using namespace std;
#include <string>
////////////////////////////
class Base {
public: #if 0
virtual ~Base();// in Child::~Child() in Base::~Base()
#else
~Base(); // in Base::~Base() 存在内存泄漏的危险
#endif
}; Base::~Base()
{
cout<<"in Base::~Base()"<<endl;
}
//////////////////////////// class Child: public Base {
public:
~Child();
}; Child::~Child()
{
cout<<"in Child::~Child()"<<endl;
} int demo()
{
Base *pc = new Child;
cout<<"-----------"<<endl;
delete pc;
cout<<"-----------"<<endl;
return ;
} int main() {
demo();
while();
return ;
}