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

核能气质少年 提交于 2020-02-01 08:21:27

问题


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.



来源:https://stackoverflow.com/questions/39632563/what-happens-when-delete-a-polymorphic-object-without-a-virtual-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!