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

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



  • 相关阅读:
    JavaScript核心参考
    面向对象的程序设计之工厂模式
    ES6中promise的使用方法
    详解 Vue 2.4.0 带来的 4 个重大变化
    Vue.js 1.x 和 2.x 实例的生命周期
    表单控件的全面分析
    元素的一些常用属性
    为表格增加的方法
    Element类型知识大全
    6-3.斜体标签
  • 原文地址:https://www.cnblogs.com/findumars/p/3070213.html
Copyright © 2011-2022 走看看