首页 > 解决方案 > GCC中vtable的第一个地址?

问题描述

当我构建、拆解和清理这个短程序时:

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. ...

我不明白0atvtable[0]是什么,但是在发现了这个其他SO 问题之后,我写了另一个例子来理解这个偏移量

https://godbolt.org/z/eWScPK

这个使用虚拟继承。

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()

所以我能够解释第一个0变成 的4,但我仍然无法解释我的 vtable 的新结构。

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

标签: c++gccpolymorphismvtable

解决方案


推荐阅读