天天看點

避免多态中未實作基類虛析構函數引起記憶體洩漏的方法

我們可以通過在子類中定義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