关键词搜索

源码搜索 ×
×

为什么析构函数通常很虚?

发布2014-11-30浏览7572次

详情内容

       前面我们已经说过, 构造函数不可以为虚函数。 现在, 我们要说, 析构函数可以为虚函数, 而且通常需要为虚函数。 先看一个简单的程序:

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. A()
  7. {
  8. cout << "A constructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. B()
  15. {
  16. cout << "B constructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. new B; // 如果是B b; 也会先后调用两个构造函数
  22. return 0;
  23. }

      结果:

 

A constructor
B constructor

 

     继续看:

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. ~A()
  7. {
  8. cout << "A destructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. ~B()
  15. {
  16. cout << "B destructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. new B;
  22. return 0; // 程序结束后,不会调用任何析构函数
  23. }


     继续看:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. ~A()
  7. {
  8. cout << "A destructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. ~B()
  15. {
  16. cout << "B destructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. B b;
  22. return 0; // 程序结束后,会先后调用B,A的析构函数
  23. }

 

 

      继续看:

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. ~A()
  7. {
  8. cout << "A destructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. ~B()
  15. {
  16. cout << "B destructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. B *pb = new B;
  22. delete pb; // 程序会先后调用B, A的析构函数
  23. return 0;
  24. }


      关键的问题来了, 我们知道, C++中经常用到多态, 经常用基类指针指向派生类对象, 所以下面程序有bug:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. ~A()
  7. {
  8. cout << "A destructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. ~B()
  15. {
  16. cout << "B destructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. A *p = new B;
  22. delete p; // bug, 只调用到了基类A的析构函数, 不符合预期
  23. return 0;
  24. }

     修改后为:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6. virtual ~A()
  7. {
  8. cout << "A destructor" << endl;
  9. }
  10. };
  11. class B : public A
  12. {
  13. public:
  14. ~B()
  15. {
  16. cout << "B destructor" << endl;
  17. }
  18. };
  19. int main()
  20. {
  21. A *p = new B;
  22. delete p; // ok, 会先后调用B,A的析构函数
  23. return 0;
  24. }


      可见, 析构函数通常要虚。如果不把析构函数设置为虚函数, 会不知不觉地引起很多错误, 比如最常见最可让人伤心的内存泄露微笑

 

 

 

 

 



 

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载