多态类中的虚拟析构函数 [英] Virtual destructor in polymorphic classes

查看:172
本文介绍了多态类中的虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,只要您有一个多态基类,该基类都应定义一个虚拟析构函数.这样,当删除指向派生类对象的基类指针时,它将首先调用派生类的析构函数.如果我错了,请纠正我.

此外,如果基类析构函数是非虚拟的,则删除指向派生对象的基类指针将是未定义的行为.如果我也错了,请纠正我.

所以我的问题是:为什么确切的说,当基类析构函数是非虚拟的时,该对象将无法正确销毁?

我假设这是因为虚拟函数具有某种表,每当调用虚拟函数时都会存储并查询该表.而且编译器知道应该删除对象时,应首先调用派生的析构函数.

我的假设正确吗?

解决方案

如果在删除对象时变量的静态类型为bas类型,则将调用基本类型的析构函数,但是子类的析构函数将不会被调用(因为它不是虚拟的).

结果是,基类分配的资源将被释放,而子类分配的资源将不会被释放.

因此无法正确破坏对象.

您对该表是正确的:它称为虚拟方法表或"vtable".但是,析构函数是非虚拟的,其结果并非不是没有以正确的顺序调用析构函数,而是根本没有调用子类的析构函数!

I understand that whenever you have a polymorphic base class, the base class should define a virtual destructor. So that when a base-class pointer to a derived-class object is deleted, it will call the destructor of the derived class first. Correct me if i am wrong here.

also, if the base-class destructor were to be non-virtual, it would be undefined behavior to delete a baseclass pointer to a derived object. Correct me if i am wrong aswell.

so my question is: Why is it exactly, that when the base-class destructor is non-virtual, the object will not be destroyed correctly?

i am assuming this is because virtual functions have some kind of table that is memorized and consulted whenever a virtual function is called. And the compiler knows that when an object is supposed to be deleted, it should call the derived destructor first.

is my assumption correct?

解决方案

If at the point where you delete the object the static type of the variable is the bas type, than the destructor of the base type will be called, but the destructor of the sub class won't be called (as it is not virtual).

As a result the resources allocated by the base class will be freed, but the resources allocated by the sub class won't.

Thus the object won't be destructed correctly.

You are correct about that table: it is called a virtual method table or "vtable". But the result of the destructor being non-virtual is not that the destructors are not called in the correct order, but that the destructor(s) of the sub class(es) are not called at all!

这篇关于多态类中的虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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