c++ - 如何让虚拟析构函数在 C++ 中被调用?

标签 c++ c++11 virtual virtual-destructor

我正在尝试查看调用属于长层次结构链的类的虚拟析构函数的效果:A 类到 E 类。

奇怪的是,析构函数不会向控制台写入任何内容。我首先想到它可能正在发生,因为 main 也在退出。因此,我将所有测试代码放在一个名为 test() 的函数中,并从 main() 中调用,因此当测试返回时,我会看到析构函数足迹。但是,什么都没有!控制台上没有出现“cout”标志!

#include <iostream>

using namespace std;

//A constructor cannot be virtual but a destructor can.
class A {
public:
A() {
    cout << "A constructor" << endl;
}
virtual ~A() {cout << "A destructor" << endl;}
};

class B :public A {
public:
    B() {
    cout << "B constructor" << endl;
    }
    virtual ~B() {cout << "B destructor" << endl;}
};

class C :public B {
public:
    C() {
    cout << "C constructor" << endl;
    }
    virtual ~C() {cout << "C destructor" << endl;}
};

class D :public C {
public:
    D() {
    cout << "D constructor" << endl;
    }
    ~D() {cout << "D destructor" << endl;}
};

class E :public D {
public:
    E() {
     cout << "E constructor" << endl;
      }
     ~E() {cout << "E destructor" << endl;}
};

void test() {
   cout << "Test1 begins..." << endl;
   A* a1 = new D();
   cout << "Test2 begins..." << endl;
   A* a2 = new E();
}

int main() {
 test();
 return 0;
}

最佳答案

嗯……你实际上泄露了那些。

每个由 new 关键字创建的对象都必须有一个等价的 delete:

void test() {
   cout << "Test1 begins..." << endl;
   A* a1 = new D();
   cout << "Test2 begins..." << endl;
   A* a2 = new E();
   delete a1;
   delete a2;
}

开发人员(就您而言)总是忘记删除动态分配的对象,因此引入了智能指针:

void test() {
   cout << "Test1 begins..." << endl;
   std::unique_ptr<A> a1(new D());
   cout << "Test2 begins..." << endl;
   std::unique_ptr<A> a2(new E());
}

无需担心泄漏,因为 unique_ptr 会在指针超出范围时自动删除它们的指针。

关于c++ - 如何让虚拟析构函数在 C++ 中被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54494767/

相关文章:

c++ - 为什么加 "const"就解决了 "invalid operands to binary expression"

c++ - 将指针和 const 添加到 std::tuple<Types...>

c++ - 类型在编译时已知的虚拟方法

c++ - 我可以从基类指针访问派生类的非虚函数吗?

C++ 整数连接

c++ - 使用 Libcurl 将非常大的字符串发送到使用 REST API 的服务器?

c++ - 如何在 Matlab MEX 中使用 mexErrMsgTxt() 打印 __LINE__ 等 C 预处理器变量

c++ - 我可以将流运算符与绑定(bind)一起使用吗?

c++ - 为什么这个 c++ 代码不能在 g++ 4.8.2 中编译

c++ - 为什么没有虚拟析构函数不会导致内存泄漏?