仮想継承が実際にどのように機能するかをよりよく理解しようとしています (つまり、標準に従ってではなく、 のような実際の実装でg++
)。実際の質問は、太字で下にあります。
そこで、継承グラフを自分で作成しました。これには、とりわけ次の単純な型があります。
struct A {
unsigned a;
unsigned long long u;
A() : a(0xAAAAAAAA), u(0x1111111111111111ull) {}
virtual ~A() {}
};
struct B : virtual A {
unsigned b;
B() : b(0xBBBBBBBB) {
a = 0xABABABAB;
}
};
(仮想継承が理にかなっているように、階層全体にC: virtual A
andもあります。)BC: B,C
インスタンスのレイアウトをダンプする関数をいくつか作成しました。vtable ポインターを取得し、最初の 6 つの 8 バイト値 (画面に収まるように任意) を出力してから、オブジェクトの実際のメモリをダンプします。これは次のようになります。
A
オブジェクトのダンプ:
actual A object of size 24 at location 0x936010
vtable expected at 0x402310 {
401036, 401068, 434232, 0, 0, 0,
}
1023400000000000aaaaaaaa000000001111111111111111
[--vtable ptr--]
B
オブジェクトのダンプと、オブジェクトが配置されている場所。これは、それぞれの位置にA
多くの s を出力することで示されます。A
actual B object of size 40 at location 0x936030
vtable expected at 0x4022b8 {
4012d2, 40133c, fffffff0, fffffff0, 4023c0, 4012c8,
}
b822400000000000bbbbbbbb00000000e022400000000000abababab000000001111111111111111
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA (offset: 16)
ご覧のとおり、のA
部分は、オブジェクトの先頭からバイトB
のオフセットに配置されています (これは、インスタンス化して!に dyn キャストした場合は異なる可能性があります)。16
B
BC
B*
プログラムは実行時に の実際の位置 (オフセット) を検索する必要があるため、 (または、アライメントのために16
少なくとも a )が table のどこかに表示されると予想していました。では、レイアウトは実際にどのように見えるのでしょうか。2
A
編集:ダンプはdump
andを呼び出すことによって行われdumpPositions
ます:
using std::cout;
using std::endl;
template <typename FROM, typename TO, typename STR> void dumpPositions(FROM const* x, STR name) {
uintptr_t const offset {reinterpret_cast<uintptr_t>(dynamic_cast<TO const*>(x)) - reinterpret_cast<uintptr_t>(x)};
for (unsigned i = 0; i < sizeof(FROM); i++) {
if (offset <= i && i < offset+sizeof(TO))
cout << name << name;
else
cout << " ";
}
cout << " (offset: " << offset << ")";
cout << endl;
}
template <typename T> void hexDump(T const* x, size_t const length, bool const comma = false) {
for (unsigned i = 0; i < length; i++) {
T const& value {static_cast<T const&>(x[i])};
cout.width(sizeof(T)*2);
if (sizeof(T) > 1)
cout.fill(' ');
else
cout.fill('0');
cout << std::hex << std::right << (unsigned)value << std::dec;
if (comma)
cout << ",";
}
cout << endl;
}
template <typename FROM, typename STR> void dump(FROM const* x, STR name) {
cout << name << " object of size " << sizeof(FROM) << " at location " << x << endl;
uintptr_t const* const* const vtable {reinterpret_cast<uintptr_t const* const*>(x)};
cout << "vtable expected at " << reinterpret_cast<void const*>(*vtable) << " {" << endl;
hexDump(*vtable,6,true);
cout << "}" << endl;
hexDump(reinterpret_cast<unsigned char const*>(x),sizeof(FROM));
}