为什么 VTT 中有 GCC 实施的top_offset?
Why is there a top_offset in VTT implemented by gcc?
这是在投票最多的答案中对VTT的详细说明。但答案并不能解释为什么 VTT 中有top-offset
。
在我看来,当我们down_cast
指向derived
指针的base
指针时,编译器已经知道编译时(没有虚拟派生时(需要调整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
仅在虚拟继承中需要。
void *top(B *b) { return dynamic_cast<void *>(b); }
编译器无法在编译时确定正确的偏移量是什么。可以使用 null 指针、指向完整B
对象的指针或指向B
子对象的指针来调用此函数。这三种情况需要以不同的方式处理。vtable 中的偏移量是允许它工作的原因。
相关文章:
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- OpenGL glBufferSubData Offset issue
- 在我自己的堆栈中实现top的问题
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- "runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088"
- "top"值不会改变我推送或弹出堆栈的次数
- NDK 构建中的异常"error: expected ';' after top level declarator"
- std::move() with priority_queue.top()
- priority_queue.top() 不返回正确的对象
- 使用 top() 时收到错误"cannot dereference out of range deque iterator"
- C++ priority_queue pop() and top() discrepancy
- QPixmap,如何确保它是'always on top'
- 当队列为空时,priority_queue pop()和top()的C++行为
- 调用 emptyStack.top() 时返回的内容
- 如何使深渊中的对象易于配置"from the top"?
- 在老板层次结构中查找"top"老板仅适用于某些测试用例
- 在Linux上使用QT,有没有办法禁用"Always on Top"?
- 如何将崩溃的"Fault offset"与源代码相匹配?
- 如何实现stack :: top()函数