如何在C++中调用虚拟析构函数

How to get virtual destructors to be called in C++?

本文关键字:调用 虚拟 析构函数 C++      更新时间:2023-10-16

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

奇怪的是,析构函数不会向控制台写入任何内容。我首先想到也许它正在发生,因为主要也退出了。因此,我将所有测试代码放在一个名为test()的函数中,并从main()中调用,因此当test返回时,我会看到析构函数足迹。但是,什么都没有!控制台上没有"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自动删除它们的尖头。

你从不delete你的原始指针。更喜欢智能指针而不是原始指针。

您应该添加

delete a1;
delete a2;

接近你的test结束时.

还尝试创建一些 E 实例作为自动变量(通常在调用堆栈上)。例如,插入

E ee;

介于这两个delete -s 之间。