简体   繁体   English

为什么不将虚拟类的析构函数自动添加到vtable?

[英]Why is not the destructor of a virtual class automatically added to the vtable?

When virtual class B derives from a virtual base class A, unless explicitly declaring a virtual destructor in A and B, B's destructor in the vtable will point to A's destructor. 当虚拟类B从虚拟基类A派生时,除非在A和B中明确声明虚拟析构函数,否则vtable中B的析构函数将指向A的析构函数。 Why? 为什么? Why doesn't the B's vtable destructor point on B's destructor automatically without having to define A and B virtual destructors? 为什么在不定义A和B虚拟析构函数的情况下B的vtable析构函数不会自动指向B的析构函数?

edit: realized that without making A's destructor virtual, B's destructor isn't even in the vtable so when calling A's destructor it justs direct calls A's. 编辑:意识到没有将A的析构函数虚拟化,B的析构函数甚至不在vtable中,因此在调用A的析构函数时,它只是直接调用A的。 My question doesn't make sense. 我的问题没有道理。

C++ works on the principle of "you don't pay for what you don't use". C ++的工作原理是“您不用为不使用的东西付费”。 Forcing the destructor of any class that has any virtual function to be virtual, even if the clients of the class never delete objects of that class polymorphically (ie through a base pointer), is a non-zero cost (slot in the vtable, deletes on the object needing a virtual function call). 强制将具有任何虚函数的任何类的析构函数虚拟化,即使该类的客户端从不多态删除该类的对象(即通过基本指针),也是非零成本(vtable中的插槽,删除)需要虚拟函数调用的对象上)。 Therefore, C++ doesn't do that without explicit instruction. 因此,C ++在没有显式指令的情况下不会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++虚拟析构函数和vtable - C++ virtual destructor & vtable 析构函数中对“类的 vtable”的未定义引用 - undefined reference to `vtable for Class` in destructor 虚拟析构函数和Vtable之间是否有任何关系 - Is there any relation between Virtual destructor and Vtable 为什么派生类中的虚析构函数为空? - Why the virtual destructor in derived class is empty? 如果您的基类有一个虚拟析构函数,那么您自己的析构函数将自动为虚拟 - if your base class has a virtual destructor, your own destructor is automatically virtual 默认析构函数可以自动生成为虚拟析构函数吗? - Can the default destructor be generated as a virtual destructor automatically? 为什么要使用虚拟析构函数? - Why virtual destructor? 为什么在启动Drive实例时,基类和Drive类具有相同的虚拟指针,但2个vtable - why Base class and Drive class have same virtual pointer but 2 vtable when initiate a Drive instance 当派生类的析构函数是非虚拟的时,为什么基类析构函数在派生对象上调用? - Why is base-class destructor called on derived object when destructor of derived class is non-virtual? 为什么派生类析构函数被调用,即使基类析构函数不是虚拟的,如果将对象创建为引用 - Why derived class destructor called even though base class destructor is not virtual if object is created as reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM