我编写了这个非常简单的 C++ 程序,我想知道为什么编译器会跨两个指针取消引用来布置 vtable。这是 C++ 程序:
class Foo {
public:
virtual void bar() {
}
};
int main(int argc, char *arv[]) {
Foo foo;
Foo *foo_p(&foo);
foo_p->bar();
}
现在,我可以查看编译器生成的程序集:
$ g++ -ggdb -Wall -O0 -S test.cpp
以下是相关部分:
.loc 1 9 0
leaq -16(%rbp), %rax # put the address of 'foo' in %rax
movq %rax, %rdi # use it as the first argument of the following function
call _ZN3FooC1Ev # call the Foo constructor
.loc 1 10 0
leaq -16(%rbp), %rax # put the address of 'foo' in %rax
movq %rax, -24(%rbp) # create 'foo_p' on the stack
.loc 1 11 0
movq -24(%rbp), %rax # load 'foo_p' into %rax
movq (%rax), %rax # dereference the pointer, put it in %rax
# %rax now holds the hidden pointer in 'foo', which is the vtable pointer
movq (%rax), %rdx # dereference the pointer ::again:: (with an offset of 0), put it in %rdx
# %rdx now holds a function pointer from the vtable
movq -24(%rbp), %rax # create the 'this' pointer (== foo_p) and put it in %rax
movq %rax, %rdi # use the 'this' pointer as the first argument to the following function
call *%rdx # call Foo::bar (via the vtable)
为什么第二个指针取消引用是必要的?为什么对象中的“隐藏”vtable 指针不直接指向 vtable?
编辑:它 ::is:: 直接指向 vtable。我只是对我的指针感到困惑:-P