What happens when delete a polymorphic object with

2020-07-25 10:49发布

问题:

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?

回答1:

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.



回答2:

By fact it depends from target compiler and in common case

delete b;

is call of the descructor function for type of b and then free allocated memory. So if the destructor is virtual then called function from virtual table (~Derived) but if is not then called function from the class (~Base). Expected result: ~Base only will be called.