virtual 析构函数

转载地址:http://blog.chinaunix.net/uid-25808509-id-3026857.html

有时候我们需要用基类的指针删除其子类的对象,这时候要非常注意,倘若基类的析构函数是 non-virtual析构函数,那么事实上,只有基类的析构函数被调用,派生类的析构函数并没有被调用,这可能会导致资源泄漏。为避免这中情况发生,我们可以将基类的析构函数声明为virtual,这样的话,子类对象才能被完全销毁.


#include <iostream>
#include <stdlib.h>
#include <crtdbg.h>

#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif

using namespace std;

class BaseClass
{
public:
    virtual ~BaseClass() = 0;
    //~BaseClass();
};

BaseClass::~BaseClass()
{
    cout << "the ~BaseClass is called" << endl;
}

class DerivedClass : public BaseClass
{
public:
    DerivedClass(int x, int y)
        :X(x)
        ,Y(y)
    {
        a = new int[y];
    }

    ~DerivedClass()
    {
        cout << "the ~Derivedclass is called" << endl;
        if(a)
        {
            delete a;
            a = NULL;
        }
    }


private:
    int X;
    int Y;
    int *a;
};

void main()
{
    //memory check
    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

    BaseClass *bs= new DerivedClass(2, 3);

    delete bs;

    system("pause");

}

程序运行结果为

the ~Derivedclass is called
the ~BaseClass is called

基类和派生类的析构函数都被调用

倘若基类的析构函数为~BaseClass();即 non-virtual 析构函数,

程序运行结果为

the ~BaseClass is called,

只有基类的析构函数被调用,子类中指针 a 指向的内存并没有被释放

Dumping objects ->
e:\work\test\test\test.cpp(287) : {128} normal block at 0x00395E38, 12 bytes long.
 Data: <            > CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

12 字节的内存泄漏了


因此,只有当一个类被用来作为基类的时候,才会把析构函数写成虚函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值