这是一个detailed description of VTT在投票最多的答案中。但答案没有解释为什么 VTT 中有 top-offset
。
从我的观点来看,当我们down_cast
一个base
指针到derived
指针时,编译器已经知道offset
需要在编译时调整(没有虚推导时),所以下面的情况不需要存储top_offset
:
class A {
public:
int a;
};
class B {
public:
int b;
virtual void w();
};
class C : public A, public B {
public:
int c;
};
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
仅在虚拟继承中需要。
最佳答案
void *top(B *b) { return dynamic_cast<void *>(b); }
编译器无法在编译时确定正确的偏移量是多少。可以使用空指针、指向完整 B
对象的指针或指向 B
子对象的指针来调用此函数。这三种情况需要区别对待。 vtable 中的偏移量允许它工作。
关于c++ - 为什么gcc实现的VTT中会有top_offset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317010/