virtual 析构函数

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

  4. #ifdef _DEBUG
  5. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  6. #endif

  7. using namespace std;

  8. class BaseClass
  9. {
  10. public:
  11.     virtual ~BaseClass() = 0;
  12.     //~BaseClass();
  13. };

  14. BaseClass::~BaseClass()
  15. {
  16.     cout << "the ~BaseClass is called" << endl;
  17. }

  18. class DerivedClass : public BaseClass
  19. {
  20. public:
  21.     DerivedClass(int x, int y)
  22.         :X(x)
  23.         ,Y(y)
  24.     {
  25.         a = new int[y];
  26.     }

  27.     ~DerivedClass()
  28.     {
  29.         cout << "the ~Derivedclass is called" << endl;
  30.         if(a)
  31.         {
  32.             delete a;
  33.             a = NULL;
  34.         }
  35.     }


  36. private:
  37.     int X;
  38.     int Y;
  39.     int *a;
  40. };

  41. void main()
  42. {
  43.     //memory check
  44.     _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

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

  46.     delete bs;

  47.     system("pause");

  48. }

程序运行结果为

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 字节的内存泄漏了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值