天天看点

避免多态中未实现基类虚析构函数引起内存泄漏的方法

我们可以通过在子类中定义static类型的析构函数,进行强制转换来避免多态情况下未将基类析构函数定义为虚函数而造成的内存泄漏的错误

#include <iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Construct Base()" << endl;
    }

    ~Base()
    {
        cout << "Destruct ~Base()" << endl;
    }

    virtual void Func(void)
    {
        cout << "Base::Func()" << endl;
    }
};

class Test : public Base
{
public:
   // 创建子类对象
static Base *CreateNew()
    {
        return new Test();
    }
    
    // 强制转换,显示释放基类空间
    static int ReleaseNew(Base *objPtr )
    {
        delete (Test *)objPtr;
        return 0;
    }

    Test()
    {
        cout << "Construct Test()" << endl;
    }

    ~Test()
    {
        cout << "Destruct ~Test()" << endl;
    }

    virtual void Func(void)
    {
        cout << "Test::Func()" << endl;
    }
};

int main()
{
    Base *obj = Test::CreateNew();
    obj->Func();
    Test::ReleaseNew(obj);
    return 0;
}      

转载于:https://www.cnblogs.com/shanwenbin/archive/2012/12/18/2822581.html