我试图通过以下示例来理解 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;
最佳答案
当您使用基指针销毁派生对象并且析构函数不是虚拟的时,您最终会遇到“未定义行为”的情况。
N3690, 5.3.5 [expr.delete] - 3
In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined
github 存储库中给出的解释完全错误(“未调用派生析构函数但未发生内存泄漏”)。你不能指望这一点。
我没有阅读其余部分,因为这会浪费时间。 UB 就是 UB...试图描述未定义是无稽之谈。
关于C++ 虚拟性示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19174529/