C++ - 虚构造函数

  1. 简介

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 关键字就可以了

欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 qinhan_shu@163.com

文章标题:C++ - 虚构造函数

本文作者:QinHan

发布时间:2020-01-11, 23:31:59

最后更新:2020-02-20, 05:42:12

原始链接:https://qinhan.site/2020/01/11/cpp-virtual-destructor/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏