删除没有虚拟析构函数的多态对象时会发生什么? [英] What happens when delete a polymorphic object without a virtual destructor?
问题描述
在下面的示例中,b
是多态指针类型,其静态类型为Base*
,其动态类型为Derived*
.
In following example, b
is a polymorphic pointer type whose static type is Base*
and whose dynamic type is Derived*
.
struct Base
{
virtual void f();
};
struct Derived : Base
{
};
int main()
{
Base *b = new Derived();
// ...
delete b;
}
在没有虚拟析构函数的情况下删除b
会发生什么?
What happens when b
is deleted without a virtual destructor?
推荐答案
在没有虚拟析构函数的情况下删除b会发生什么?
What happens when b is deleted without a virtual destructor?
我们不知道.该行为是未定义的.在大多数实际情况下,可能不会调用Derived
的析构函数,但不能保证任何结果.
We don't know. The behavior is undefined. For most actual cases the destructor of Derived
might no be invoked, but nothing is guaranteed.
(重点是我的)
在第一个替代方案(删除对象)中,如果 要删除的对象与其动态类型(静态)不同 type应该是要动态对象的动态类型的基类 删除且静态类型应具有虚拟析构函数或 行为未定义.
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.
这篇关于删除没有虚拟析构函数的多态对象时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!