C/C++沉思-----多态时一定要将父类(基类)的析构函数定义为虚函数

转自:https://blog.csdn.net/qiurisuixiang/article/details/6926313

 

先来看一段代码:

 
  1. //test.cpp

  2. #include <iostream>

  3. using namespace std;

  4.  
  5. class father

  6. {

  7. public:

  8. father()

  9. {

  10. mPtr = new int;

  11. }

  12.  
  13. ~father()

  14. {

  15. delete mPtr;

  16. cout << "father Destruction......" << endl;

  17. }

  18.  
  19. private:

  20. int *mPtr;

  21. };

  22.  
  23.  
  24. class son:public father

  25. {

  26. public:

  27. son()

  28. {

  29. mStr = new long;

  30. }

  31.  
  32. ~son()

  33. {

  34. delete mStr;

  35. cout << "son Destruction......" << endl;

  36. }

  37.  
  38. private:

  39. long *mStr;

  40. };

  41.  
  42.  
  43. int main()

  44. {

  45. father *p = new son;

  46. delete p;

  47. return 0;

  48. }


 

程序运行截图:

 

从程序的运行结果来看,程序最后只释放了父类的内存,子类的内存并没有释放。则这段程序产生了内存泄露。那是什么原因导致的呢?

在main函数中new出来的是子类son的对象,采用一个父类father的指针来接收,故在析构的时候,编译器因为只知道这个指针是父类的,所以只将父类部分的内存析构了,而不会去析构子类的内存,就造成了内存泄露,那么如何避免这种情况的产生呢?

将父类的析构函数改为虚函数,就可以避免这种情况。

 
  1. //test.cpp

  2. #include <iostream>

  3. using namespace std;

  4.  
  5. class father

  6. {

  7. public:

  8. father()

  9. {

  10. mPtr = new int;

  11. }

  12.  
  13. virtual~father()

  14. {

  15. delete mPtr;

  16. cout << "father Destruction......" << endl;

  17. }

  18.  
  19. private:

  20. int *mPtr;

  21. };

  22.  
  23.  
  24. class son:public father

  25. {

  26. public:

  27. son()

  28. {

  29. mStr = new long;

  30. }

  31.  
  32. ~son()

  33. {

  34. delete mStr;

  35. cout << "son Destruction......" << endl;

  36. }

  37.  
  38. private:

  39. long *mStr;

  40. };

  41.  
  42.  
  43. int main()

  44. {

  45. father *p = new son;

  46. delete p;

  47. return 0;

  48. }


 

程序运行截图:

 

从程序的运行结果可以看出,父类和子类的内存都被析构了。所以在使用多态时一定要将父类的析构函数定义成虚函数,从而避免内存泄露。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值