c++ - 您如何确保调用 Derived 析构函数?

标签 c++ destructor

#include <iostream>

using namespace std;

class Base
{
    public:
        Base ( )
        {
            cout << "Inside Base constructor" << endl;
        }

        ~Base ( )
        {
            cout << "Inside Base destructor" << endl;
        }

};

class Derived : public Base
{
    public:    
        Derived  ( )
        {
        cout << "Inside Derived constructor" << endl;
        }

        ~Derived ( )
        {
            cout << "Inside Derived destructor" << endl;
        }
};

class Derived2 : public Base
{
    public:
        static void bogus(Derived2* d)
        {
            cout << "bogus" << endl;
        }

        Derived2  ( )
        {
            cout << "Inside Derived2 constructor" << endl;
        }

        ~Derived2 ( )
        {
            cout << "Inside Derived2 destructor" << endl;
        }
};

int main( )
{
    Derived y;
    Derived2::bogus( new Derived2 ());

    return 0;
}

-

>Inside Base constructor
>Inside Derived constructor
>Inside Base constructor
>Inside Derived2 constructor
>bogus
>Inside Derived destructor
>Inside Base destructor
>Press <RETURN> to close this window...

我在测试一些东西时发现了这种奇怪的行为。当我们在参数字段中创建对象时,为什么不调用析构函数?是否有任何解决方案,是否需要,是否存在内存泄漏?

最佳答案

首先 - 当您使类彼此派生时,您应该确保析构函数是虚拟的。如果不这样做,则当派生类具有其他成员时可能会发生内存泄漏:

virtual ~Base ( )
{
  cout << "Inside Base destructor" << endl;
}

其次 - 当您使用 new 分配内存时,不会在创建的对象上调用析构函数,直到您使用 delete 手动删除它:

int main( )
{
  Derived y;
  Derived2 *ptr = new Derived2();
  Derived2::bogus(ptr);
  delete ptr;
  return 0;
}

如果您不确定何时删除对象,请使用std::shared_ptr 或在类的析构函数中将其删除,将其作为参数。请注意,shared_ptr 仅适用于 C++11,如果您使用的是旧版本(仍然有很多人使用),请尝试使用 boost 库。

关于c++ - 您如何确保调用 Derived 析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566512/

相关文章:

c++ - 从 std::vector<std::vector<T>> 中删除任意项目列表

c++ - "... ..." token 是什么意思?即参数包上的双省略号运算符

c++ - 静态成员变量的构造函数和析构函数(指针)

c++ - C++ 中模板和 STL 的缺点

c++ - 分段故障打印文件特征

node.js - 当我的对象即将被 Node 中的 GC 收集时,我可以得到回调吗?

c++ - 带有模板关键字的伪析构函数调用

c++ - 为什么析构函数在 C++ 中运行两次?

c++ - 删除指针成员变量的数组内存

c++ - 如何检查技术规范 (TS) 是否可用?