C++ GCC中vtable的第一个地址?

C++ GCC中vtable的第一个地址?,c++,gcc,polymorphism,vtable,C++,Gcc,Polymorphism,Vtable,当我构建、demangle和clean这个短程序时: struct Base { virtual int compute() { return 42; } }; struct Derived: public Base { int compute() override { return 23; } }; int main() { Base* a = new Derived; a->compute(); } 我用一些自制的魔法来做: g++ -g -o-

当我构建、demangle和clean这个短程序时:

struct Base {
    virtual int compute() { return 42; }
};

struct Derived: public Base {
    int compute() override { return 23; }
};

int main() {
    Base* a = new Derived;
    a->compute();
}
我用一些自制的魔法来做:

g++ -g -o- -S foo.cpp | \
    c++filt | \
    perl -pe 's/^\.LA\w+:\r?\n//gm' | \
    perl -0777 -pe 's/^\.Ldebug\w+:\r?\n(\s+\..+?\r?\n)+//gm' | \
    perl -pe 's/^\.L\w+:\r?\n//gm' | \
    perl -pe 's/^\s+\.(align|section|weak|loc|file|cfi).+\r?\n//gm' | \
    highlight --out-format=ansi --syntax=asm
我明白了:

vtable for Derived:
        .quad   0
        .quad   typeinfo for Derived
        .quad   Derived::compute()
        .type   vtable for Base, @object
        .size   vtable for Base, 24
vtable for Base:
        .quad   0
        .quad   typeinfo for Base
        .quad   Base::compute()
        .type   typeinfo for Derived, @object
        .size   typeinfo for Derived, 24
我注意到我的
vtable
具有以下结构:

0. ???
1. Pointer to typeinfo
2. Pointer to first virtual method
3. Pointer to second virtual method
4. ...
我不明白
vtable[0]
上的
0
是什么,但在发现了这个问题后,我又写了一个例子来理解这个向顶部偏移的问题

这一个使用虚拟继承

struct Top {
    virtual void foo() { }
};

struct Left: public Top { // note: non virtual
    void foo() override { }
};

struct Right: virtual public Top {
    void foo() override { }
};
// note: Bottom is not a "diamond", Top is base twice
struct Bottom: public Left, public Right {
    void foo() override { }
};

int main() {
    Bottom bottom;
    bottom.foo();
}
这次我的
vtable
如下所示:

vtable for Bottom:
        .word   4
        .word   0
        .word   typeinfo for Bottom
        .word   Bottom::foo()
        .word   0
        .word   -4
        .word   -4
        .word   typeinfo for Bottom
        .word   non-virtual thunk to Bottom::foo()
因此,我能够解释第一个成为
4
0
,但我仍然无法解释vtable的新结构


我正在寻找一个更详细的答案来解释后一个例子

尝试虚拟继承。0是否更改?虚拟继承意味着一个或多个虚拟基类。如果这仍然没有任何意义,那么快速搜索“虚拟基类”应该会很有启发性。@StoryTeller是的,它会随着而改变,但它会生成其他问题,因为后面还有一个0。我将编辑我的问题每个基础对象都需要知道从该基础到最派生对象的距离。还有每个虚拟基地的位置。请注意,主基地共享其vptr,虚拟基地可以是主基地,也可以不是,这取决于完整的布局<代码>顶部在<代码>左侧中为主,在<代码>底部中主<代码>顶部在完整的
右侧
中是主要的,也在
右侧
底部的底部(我认为);因此,使用
比使用
更有效(略)。[在我注意到
左侧没有虚拟继承后更正了评论
!]