Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}

What happens when b is deleted without a virtual destructor?

like image 705
msc Avatar asked Feb 18 '26 23:02

msc


1 Answers

What happens when b is deleted without a virtual destructor?

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 Delete [expr.delete]

(emphasis mine)

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.

like image 112
songyuanyao Avatar answered Feb 20 '26 11:02

songyuanyao