• C++虚析构函数


    一、基类中析构函数不加关键字virtual。

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Base
     5 {
     6 public:
     7      ~Base()
     8     {
     9         cout<<"Base Destructor"<<endl;
    10     }
    11 };
    12 
    13 class Derive : public Base
    14 {
    15 public:
    16     ~Derive()
    17     {
    18         cout<<"Derive Destructor"<<endl;
    19     }
    20 };
    21 
    22 int main()
    23 {
    24     Base *pBase = new Derive;
    25 
    26     delete pBase;
    27 
    28     return 0;
    29 }

    输出结果:
    Base Destructor

     二、基类析构函数加上关键字virtual

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Base
     5 {
     6 public:
     7     virtual ~Base()
     8     {
     9         cout<<"Base Destructor"<<endl;
    10     }
    11 };
    12 
    13 class Derive : public Base
    14 {
    15 public:
    16     ~Derive()
    17     {
    18         cout<<"Derive Destructor"<<endl;
    19     }
    20 };
    21 
    22 int main()
    23 {
    24     Base *pBase = new Derive;
    25 
    26     delete pBase;
    27 
    28     return 0;
    29 }

    输出结果:

    Derive Destructor
    Base Destructor

    可以看出,当我们用基类指针指向派生类时,如果我们delete基类的指针,如果基类析构函数不加virtual时,那么派生类的析构函数将得不到执行,那么此时就会造成内存泄漏,所以在此种情况下,我们应该把基类析构函数定义为虚析构函数,防止内存泄漏。

  • 相关阅读:
    linux tar 压缩解压缩
    JS获取图片上传地址
    ipython notebook
    docker build lnmp(未完成。。。)
    centos6.7 install chrome
    centos6.6 install
    centos 安装mysqldb 记录
    centos emacs安装
    第三周-第08章节-Python3.5-文件修改详解
    第三周-第06章节-Python3.5-文件读与写详解
  • 原文地址:https://www.cnblogs.com/Dreamcaihao/p/3078908.html
Copyright © 2020-2023  润新知