why do we need a virtual destructor with dynamic memory? [duplicate]

ぐ巨炮叔叔 提交于 2019-12-14 03:37:29

问题


Why do we need a virtual destructor with dynamic variables when we have inheritance? and what is the order for destructor execution in both the static/dynamic case? won't the destructor of the most derived class always execute first?


回答1:


Imagine you have this:

class A { 
  public:
  int* x;     
}
class B : public A {
  public:
  int *y;
}


main() {
  A *var = new B;
  delete var;
}

Please assume some constructors destructors. In this case when you delete A. If you have virtual destructors then the B destructor will be called first to free y, then A's to free x.

If it's not virtual it will just call A's destructor leaking y.

The issue is that the compiler can't know beforehand which destructor it should call. Imagine you have a if above that constructs A or B depending on some input and assings it to var. By making it virtual you make the compiler deffer the actual call until runtime. At runtime it will know which is the right destructor based on the vtable.




回答2:


You need a virtual destructor in the base class when you attempt to delete a derived-class object through a base-class pointer.

Case in pont:

class Foo
{
public:
  virtual ~Foo(){};
};

class Bar : public Foo
{
public:
  ~Bar() { std::cout << "Bye-Bye, Bar"; }
};

int main()
{
  Foo* f = new Bar;
  delete f;
}

Without the virtual destructor in the base class, Bar's destructor would not be called here.



来源:https://stackoverflow.com/questions/20957473/why-do-we-need-a-virtual-destructor-with-dynamic-memory

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