我试图通过以下示例来了解 C++ 中的破坏行为: https ://github.com/peterdemin/virtual-destruction-5-cents
该列表是否满足了所有可能的流程?应该添加什么?如何将给定的示例转换为简短的术语?
https://stackoverflow.com/a/461224/135079提出“当基类的析构函数要被多态操作时,总是使它们成为虚拟的。” 这不包括场景 4。
Scott Meyers 的 Effective C++ 中的第 7 项指出:
- 如果一个类有任何虚函数,它应该有一个虚析构函数;
- 未设计为基类或未设计为多态使用的类不应声明虚拟析构函数。
这是轻的(应该和不应该)并且面对场景2。
更新
我将6502提供的 C++ 标准重写为伪代码:
if static type of object is different from its dynamic type:
if the static type is a base class of the dynamic type:
if the static type has a virtual destructor:
We're fine - dynamic type's destructor will be called
else:
behavior is undefined [1]
else:
behavior is undefined [2]
[1] 代码将在没有警告的情况下编译,并且可能会正常工作,但不能保证并且可能会在运行时导致纠缠错误。
[2] 这很尴尬:
class A {};
class B {};
B *a = (B*)(new A());
delete a;