当我尝试访问从虚拟基类继承的派生类对象的内存布局时,出现了一些问题。
编程环境:GNU/Linux 3.19.0-32-generic,x86_64
编译器:gcc 4.8.4
//virtual base class
class Base {
public :
virtual void f() {
cout << "Base::f()" << endl;
}
private:
long x;
};
//derived class
class Derived : public virtual Base {
public:
virtual void f() {
cout << "Derived::f()" << endl;
}
private:
long y;
};
int main() {
typedef void (*FUNC)(void);
Derived d;
//In my machine, sizeof(long) == sizeof(pointers). My code below is neither portable nor concise. You can just read the annotation.
//dereference the first element of the first virtual function table(equals to *(vptr1->slot[0]))
cout << hex << *((long*)*((long*)(&d) + 0) + 0) << endl;
((FUNC)*((long*)*((long*)(&d) + 0) + 0))();//invoke Derived::f()
//dereference the first element of the second virtual function table(equals to *(vptr2->slot[0]))
cout << hex << *((long*)*((long*)(&d) + 2) + 0) << endl;
((FUNC)*((long*)*((long*)(&d) + 2) + 0))();//maybe Derived::f()?
return 0;
}
当我运行代码时,出现了"段错误(segment fault)"的提示:
400c12
Derived::f()
400c3c
segment fault
所以我对可执行文件进行了反汇编。
我在0x400c3c中找到了函数<_ZTv0_n24_N7Derived1fEv>。
0000000000400c3c <_ZTv0_n24_N7Derived1fEv>:
400c3c: 4c 8b 17 mov (%rdi),%r10
400c3f: 49 03 7a e8 add -0x18(%r10),%rdi
400c43: eb cd jmp 400c12 <_ZN7Derived1fEv>
400c45: 90 nop
在我的终端中解码符号:
> c++filt _ZTv0_n24_N7Derived1fEv
virtual thunk to Derived::f()
那么Derived::f()中的虚拟thunk是什么?它为什么存在?