我正在尝试查看调用属于长层次结构链的类的虚拟析构函数的效果: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/