【发布时间】:2018-10-23 07:52:39
【问题描述】:
这是票数最高的答案中的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;
};
在这种情况下,C 类型的对象的布局如下(数字假设为 32 位指针):
+-----------------------+
| 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只需要在虚拟继承中。
【问题讨论】:
-
只需 google “c++ 多重继承 top_offset” 即可获得点击率。
-
@HansPassant 我用谷歌搜索了,但没有找到预期的答案。
-
@bigxiao 嗯?无论当前代码是否需要某个特定部分,vtable 仍然需要相同的布局。
-
@bigxiao o11c 写的是 vtable 需要相同的 layout,而不是完全一样。显然需要相同的布局:使用
B的代码将被编译为使用一种在运行时无法更改的特定布局。该布局包括顶部偏移量。 -
@bigxiao 对于代码通过引用获取
B并使用vtable 中的任何内容,如果它不知道它是普通B还是B-in-C,如何如果它不知道 vtable 布局,它可以使用 vtable 吗?
标签: c++ memory-layout virtual-table