非指针成员变量的虚析构函数

Virtual destructor for non pointer member variables

我有一个关于虚拟析构函数的问题。我知道如果变量指针是多态的,则必须创建一个虚拟析构函数,但如果我不需要执行任何析构特定代码,是否有必要?

例如下面的代码:

struct Foo
{
    struct ExtraData
    {
        int myType;
    }
    struct BarData : public ExtraData
    {
        std::string myName;
        float myFoo;
    }
    struct BooData : public ExtraData
    {
        int myBoo;
        double myTime;
    }
    Foo() {}
    ~Foo() { delete myExtradata; }

    int myA;
    int myB;
    ExtraData* myExtraData;
};

myExtraData 是从结构外部创建的,可以通过 new BarData() 或通过 new BooData() 创建。 BarData 和 BooData 是否需要虚拟析构函数。或者因为他们没有成员指针没关系?

当您执行 delete myExtradata; 时,删除操作必须知道如何为被删除的对象调用正确的析构函数。为了使其以多态方式工作,ExtraData 需要有一个虚拟析构函数。

不仅指针需要它,而且在这种特定情况下,我确信 BarData 中的 std::string 内部至少有一个指针。

来电是UB:

Base* base = new Derived;
delete base; // UB here if ~Base is not virtual.

除非 Base 的析构函数是 virtual

5.3.5/3 Delete

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73)

在您的例子中,“操作数的静态类型”是 ExtraData,“它的动态类型”是 BarDataBooData。所以他们是不一样的,静态类型ExtraData肯定有虚析构