为什么gcc在VTT中实现了top_offset? [英] Why is there a top_offset in VTT implemented by gcc?
问题描述
此处是 VTT的详细说明,投票表决的答案.但是答案并不能解释为什么VTT中存在top-offset
.
Here is a detailed description of VTT in the top-voted answer.But the answer does not explain why is there a top-offset
in the VTT.
从我的角度来看,当我们down_cast
一个base
指针指向derived
指针时,编译器已经知道offset
需要在编译时进行调整(是没有虚拟派生的),因此无需在以下情况下存储top_offset
:
From my point of view,when we down_cast
a base
pointer to derived
pointer,the compiler already knows the offset
needed to be adjusted in compile time(when there is no virtual derivation) ,so there is no need to store a top_offset
in situation below:
class A {
public:
int a;
};
class B {
public:
int b;
virtual void w();
};
class C : public A, public B {
public:
int c;
};
在这种情况下,类型C的对象的布局如下(数字假设32位指针):
In this case, objects of type C are laid out like this (numbers assuming 32-bit pointers):
+-----------------------+
| 0 (top_offset) |//why?
+-----------------------+
c --> +----------+ | ptr to typeinfo for C |
| vtable |-------> +-----------------------+
+----------+ | A::v() |
| a | +-----------------------+
+----------+ | -8 (top_offset) |//why?
| vtable |---+ +-----------------------+
+----------+ | | ptr to typeinfo for C |
| b | +---> +-----------------------+
+----------+ | B::w() |
| c | +-----------------------+
+----------+
为什么在这种情况下VTT中会有top_offset
?我认为top_offset
和virtual base offset
仅在虚拟继承中需要.
Why is there a top_offset
in VTT under such situation? I think the top_offset
and virtual base offset
are only needed in virtual inheritance.
推荐答案
void *top(B *b) { return dynamic_cast<void *>(b); }
编译器无法在编译时确定正确的偏移量.可以使用空指针,指向完整的B
对象的指针或指向B
子对象的指针来调用此函数.这三种情况需要以不同的方式处理. vtable中的偏移量使它可以正常工作.
There is no way for the compiler to determine at compile time what the correct offset is. This function may be called with a null pointer, a pointer to a complete B
object, or a pointer to a B
subobject. The three cases need to be handled differently. The offset in the vtable is what allows this to work.
这篇关于为什么gcc在VTT中实现了top_offset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!