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

标签 c++ c++11 pointers destructor

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

例如下面的代码:

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 是否需要虚拟析构函数。或者因为他们没有成员指针,所以没关系?

最佳答案

这将是 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必须有一个虚析构函数。

关于c++ - 非指针成员变量的虚析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605184/

相关文章:

C++:修改函数,尝试重新编译,得到对该函数的 undefined reference

android - 为 Android NDK 编译 C++11 源代码

c++ - g++ 与 GSL 的链接问题

c++ - 类模板参数默认值

c++ - 模板函数中如何实现模板类类型?

c++ - 未定义对 Logger::getInstance() 的引用 - 但仅在某些情况下

c++ - 默认情况下是否创建 move 构造函数?

C- 不正确的方法需要纠正

c++ - 防止 C++(或 C++0x)中的 header 爆炸

c - 使用函数更改指针包含的地址