如何在C++中调用虚拟析构函数
How to get virtual destructors to be called in C++?
我试图看到调用属于长层次结构链的类的虚拟析构函数的效果:类 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 之间。
相关文章:
- 是否可以使用函数指针调用虚拟析构函数?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 使用在堆栈上创建的对象调用虚拟函数
- 如何从派生类函数中调用虚拟函数
- 从内部类的析构函数调用虚拟函数
- 使用范围解析运算符时,在构造函数中调用虚拟方法是否安全?
- 调用虚拟成员类的方法
- 为什么不调用虚拟基非默认构造函数,除非大多数派生基显式调用它们?
- 为什么在运行时调用虚拟函数时需要虚拟表
- 从C++中的虚拟析构函数调用虚拟方法
- 如何在C++中调用虚拟析构函数
- 调用虚拟函数而不通过类类型指针创建任何对象
- 通过命名成员调用虚拟与地址或引用的区别
- 从派生的指针中调用虚拟功能,而无需支付VTable价格
- 为什么我不能从铸造的字节(char)数组中调用虚拟函数
- 在基类崩溃中调用虚拟功能
- 可以通过跨二进制边界传递的对象上的接口调用虚拟函数吗?
- 调用虚拟方法的不同方法
- C++未根据需要调用虚拟方法