我寫了這個非常簡單的C++程序,我想知道爲什麼編譯器通過兩個指針解引用來佈置vtable。這裏的C++程序:C++ vtables中的雙重間接
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?
edit:it :: is ::直接指向vtable。我剛剛困惑着我的指針:-P
+1有沒有愚蠢的問題,如果他們準備像這樣 –