C++ - 虚构造函数

C++ 学习笔记

C++ 虚构造函数

简介

  • 首先来看一段代码,以及其执行的结果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    #include <iostream>

    class Base
    {
    public:
    Base() { std::cout << "Base Constructor. \n"; };
    ~Base() { std::cout << "Base Destructor. \n"; };
    };

    class Derived : public Base
    {
    public:
    Derived() { std::cout << "Derived Constructor. \n"; };
    ~Derived() { std::cout << "Derived Destructor. \n"; };
    };

    int main()
    {
    Base* base = new Base();
    delete base;

    std::cout << "--------\n";

    Derived* derived = new Derived();
    delete derived;

    std::cout << "--------\n";

    Base* ploy = new Derived();
    delete ploy; // 可能会导致内存泄漏

    return 0;
    }
  • 执行结果如下所示

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Base Constructor. 
    Base Destructor.
    --------
    Base Constructor.
    Derived Constructor.
    Derived Destructor.
    Base Destructor.
    --------
    Base Constructor.
    Derived Constructor.
    Base Destructor.
  • 前面两段代码的执行结果可以理解

  • 最后一段代码只执行来 Base 类的析构函数,这样就有可能造成内存泄露

  • 如何解决?

    • Base 类的析构函数上加上 virtual 关键字就可以了