在没有虚析构函数的情况下删除多态对象会发生什么?

What happens when delete a polymorphic object without a virtual destructor?

在下面的示例中,b 是一个多态指针类型,其 static 类型为 Base* 且其 dynamic 类型是 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?

我们不知道。行为未定义。对于大多数实际情况,Derived 的析构函数可能不会被调用,但没有任何保证。

5.3.5 删除 [expr.delete]

(强调我的)

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.