zoukankan      html  css  js  c++  java
  • 基类一定要设置虚析构函数,否则会内存泄露

    关于虚函数,在多态当中,一定要将基类的析构函数设置为虚函数并将其实现,只有这样,才能够达到按对象构造的逆序来析构对象;否则,析构的时候,只会析构基类的那一部分,那么派生类那一部分就无法成功析构了。当指向派生类对象的指针被删除的时候,如果析构函数是虚函数(它应该如此),那么就会正确的操作——调用派生类的析构函数。由于派生类的析构函数会自动调用基类的析构函数,结果整个对象就会正确销毁。一般规律是,只要类中的任何一个函数是虚函数,那么析构函数也应该是虚函数。

    #include <iostream>
    using namespace std;
    
    class shape
    {
    public:
        shape(){};
        virtual void draw() = 0;
        virtual ~shape(){cout << "shape destruction" << endl;}
    };
    class rectangle : public shape
    {
    public:
        rectangle(){};
        void draw()
        {
        }
        ~rectangle(){cout << "rectangle destruction" << endl;}
    };
    class round : public shape
    {
    public:
        round(){};
        void draw()
        {
        }
        ~round(){cout << "round destruction" << endl;}
    };
    void main()
    {
        shape * s;
        s = new rectangle();
        s->draw();
        delete s;
        s = new round();
        s->draw();
        delete s;
    }

    运行结果:

    rectangle destruction
    shape destruction
    round destruction
    shape destruction

    另外特意做了一个实验,把这里的virtual去掉:

    virtual ~shape(){cout << "shape destruction" << endl;}

    运行结果:

    shape destruction
    shape destruction

    没有运行子类的析构函数。



  • 相关阅读:
    七、Struts2之文件上传与下载
    八、Struts2之OGNL
    五、Struts2之类型转换
    wpf坐标转换相关
    wpf拖拽封装类
    获取Bitmap的Graphics
    Win32定时器
    vs2010调试dll
    使用GDI+ 保存HDC为位图文件
    在c++中使用.net
  • 原文地址:https://www.cnblogs.com/findumars/p/3070213.html
Copyright © 2011-2022 走看看