Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1770264
  • 博文数量: 198
  • 博客积分: 4088
  • 博客等级: 上校
  • 技术积分: 2391
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-15 16:29
个人简介

游戏开发,系统架构; 博客迁移到:http://www.jianshu.com/u/3ac0504b3b8c

文章分类

全部博文(198)

文章存档

2017年(1)

2016年(12)

2015年(1)

2014年(3)

2013年(13)

2012年(18)

2011年(150)

分类: C/C++

2011-11-24 13:39:32

 有时候我们需要用基类的指针删除其子类的对象,这时候要非常注意,倘若基类的析构函数是 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 字节的内存泄漏了

阅读(3303) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~