考虑以下具有3级多重继承层次结构的代码。
auto addr = [](auto v) -> uint64_t { return *reinterpret_cast<uint64_t*>(v); };
struct BaseA
{
void virtual a() {}
};
struct BaseB
{
void virtual b() {}
};
struct BaseC : BaseA, BaseB
{
void virtual a() override {}
void virtual b() override {}
};
struct BaseD
{
void virtual d() {}
};
struct BaseE : BaseD, BaseC
{
void virtual d() override {}
void virtual a() override {}
void virtual b() override { auto a = this; std::cout << "called here: " << addr(&a) << "\n"; }
};
int main()
{
BaseE obj;
BaseE* ePtr = &obj;
BaseD* dPtr = &obj;
BaseC* cPtr = &obj;
BaseB* bPtr = &obj;
BaseA* aPtr = &obj;
ePtr->b();
cPtr->b();
bPtr->b();
std::cout << "e is at: " << addr(&ePtr) << "\n"
<< "d is at: " << addr(&dPtr) << "\n"
<< "a is at: " << addr(&aPtr) << "\n"
<< "c is at: " << addr(&cPtr) << "\n"
<< "b is at: " << addr(&bPtr) << "\n"
<< "total size is " << sizeof(BaseE) << "\n"
<< "vptr D and E " << vpt1 << "\n"
<< "vptr A and C " << vpt2 << "\n"
<< "vptr B " << vpt3 << "\n";
return 0;
}
此代码运行的输出如下:
called here: 140736308965696
called here: 140736308965696
called here: 140736308965696
e is at: 140736308965696
d is at: 140736308965696
a is at: 140736308965704
c is at: 140736308965704
b is at: 140736308965712
total size is 24
vptr D and E 4390608
vptr A and C 4390648
vptr B 4390680
这表明BaseE obj的以下内存布局(指针大小为8字节)。
此处ePtr
和dPtr
都指向BaseD
子对象,aPtr
和cPtr
都指向BaseA
子对象和{{1} }到bPtr
子对象。
我现在的问题是编译器生成什么thunk代码,通过指针BaseB
和this
调整b()
以上两个调用中的cPtr
指针,以确保调用bPtr
的{{1}}时,this
正确指向ePtr
?由于BaseE
和b()
具有不同的地址,thunk需要知道根据传递给它的Base类指针的类型进行不同的调整吗?