我有一个关于虚拟析构函数的问题。我知道如果变量指针是多态的,则必须创建虚拟析构函数,但如果我不需要执行任何析构特定代码,是否有必要?
例如下面的代码:
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
,“它的动态类型”是 BarData
或 BooData
。所以它们是不同的,静态类型ExtraData
必须有一个虚析构函数。
关于c++ - 非指针成员变量的虚析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605184/