删除没有虚拟析构函数的多态对象时会发生什么? [英] What happens when delete a polymorphic object without a virtual destructor?

查看:137
本文介绍了删除没有虚拟析构函数的多态对象时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,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.

5.3.5删除 [expr.delete]

5.3.5 Delete [expr.delete]

(重点是我的)

在第一个替代方案(删除对象)中,如果 要删除的对象与其动态类型(静态)不同 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆