基类与接口类中的虚析构函数(virtual destructor)

一般情况下,在基类或者接口类中添加虚析构函(virtual destructor)数非常重要。原因很简单,就是想让析构的顺序从继承类开始往上开始一步步析构直到基类。

看例子吧:

首先,接口类不写虚析构函数

// virtual d'tor
// In base class or interface, it is important that add a virtual destructor
class IFoo
{
public:
    virtual void dosomething() = 0;
};

class Foo : public IFoo
{
public:
    Foo(int* pInt = NULL) : pInt(pInt){}
    virtual void dosomething()
    {
        pInt = new int[10];
        pInt[1] = 1;
        pInt[2] = 2;
    }
    ~Foo()
    {
        delete[] pInt;
    }

    int* get_pInt()
    {
        return pInt;
    }

    const int* get_pInt() const
    {
        return pInt;
    }

private:
    int* pInt;
};

去调用测试一下:

using namespace std;
int main()
{
    IFoo* f = new Foo();
    f->dosomething();
    delete f;

    return 0;
}

当执行

delete f;

时,程序并不会调用Foo类中的析构函数(因为你没在基类中写虚析构函数),所以造成内存泄露。

下面我们加上virtual destructor

class IFoo
{
public:
    virtual void dosomething() = 0;
    virtual ~IFoo(){}  // add virtual destructor
};

class Foo : public IFoo
{
public:
    Foo(int* pInt = NULL) : pInt(pInt){}
    virtual void dosomething()
    {
        pInt = new int[10];
        pInt[1] = 1;
        pInt[2] = 2;
    }
    ~Foo()
    {
        delete[] pInt;
    }

    int* get_pInt()
    {
        return pInt;
    }

    const int* get_pInt() const
    {
        return pInt;
    }

private:
    int* pInt;
};
using namespace std;
int main()
{
    IFoo* f = new Foo();
    f->dosomething();
    delete f;   // It's ok!!!

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值