C++ 虚拟性示例

标签 c++ virtual-destructor

我试图通过以下示例来理解 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/

相关文章:

c++ - 缺少 vtable 通常意味着第一个非内联虚拟成员函数没有定义

c++ - 使用非虚拟析构函数有什么具体原因吗?

c++ - 绑定(bind) Texture2D 和 TextureCube

c++ - 从 ">"运算符导出 "<"运算符

c++ - 如何在 noexcept 运算符中引用移动构造函数

c++ - 如果基类析构函数是虚拟的,是否需要派生类析构函数定义?

c++ - 析构函数和python

c++ - 使用虚拟的破坏顺序

c++ - 如何使用 FFMPEG 将 N 个实时 MP3 流合并为一个?

c++ - make 说 : `No rule to make target` when I try to compile a Qt application for android platfrom