why do we need a virtual destructor with dynamic m

2019-09-21 19:27发布

This question already has an answer here:

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?

2条回答
迷人小祖宗
2楼-- · 2019-09-21 19:55

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-21 20:01

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.

查看更多
登录 后发表回答