为什么我们需要一个带有动态内存的虚拟析构函数? [英] why do we need a virtual destructor with dynamic memory?

查看:113
本文介绍了为什么我们需要一个带有动态内存的虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在继承时我们需要带有动态变量的虚拟析构函数?在静态/动态情况下执行析构函数的顺序是什么?最派生类的析构函数不会总是先执行吗?

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?

推荐答案

想象一下您有这个:

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


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

请假定一些构造函数析构函数. 在这种情况下,当您删除A时.如果您有虚拟析构函数,则将首先调用B析构函数以释放y,然后将A释放x.

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.

如果不是虚拟的,它将仅调用A的析构函数泄漏y.

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

问题在于,编译器无法事先知道应调用哪个析构函数.想象一下,如果上面有一个if,它会根据一些输入来构造A或B并将其赋值给var. 通过使其虚拟化,可以使编译器将实际调用推迟到运行时.在运行时,它将基于vtable知道哪个是正确的析构函数.

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.

这篇关于为什么我们需要一个带有动态内存的虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆