What happens when delete a polymorphic object without a virtual destructor?
Asked Answered
P

1

3

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?

Personalism answered 22/9, 2016 at 7:14 Comment(2)
read this as well securecoding.cert.org/confluence/display/cplusplus/…Rozamond
Possible duplicate of Virtual destructor missing for base class in polymorphism = Ressource leak?Hokku
C
3

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.

Coulisse answered 22/9, 2016 at 7:18 Comment(1)
@downvoter Please tell me where I'm wrong so I can improve it.Coulisse

© 2022 - 2024 — McMap. All rights reserved.