1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <iostream> using namespace std; class Base { public: virtual ~Base() {} virtual void func() = 0; int base_; }; class SubLeft : virtual public Base { public: int subLeft_; }; class SubRight : virtual public Base { public: int subRight_; }; class Diamond : public SubLeft, public SubRight { public: void func() {} int diamond_; }; int main() { Diamond diamond; cout << "sizeof Base: " << sizeof(Base) << endl; cout << "sizeof SubLeft: " << sizeof(SubLeft) << endl; cout << "sizeof Diamond: " << sizeof(Diamond) << endl; cout << "base_ offset: " << (size_t)&diamond.base_ - (size_t)&diamond << endl; cout << "subLeft_ offset: " << (size_t)&diamond.subLeft_ - (size_t)&diamond << endl; return 1; } |
编译环境是vs2019 x64,项目属性 => C/C++ => Command Line中增加
1 | /d1reportSingleClassLayoutDiamond |
编译时输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 1>class SubLeft size(32): 1> +--- 1> 0 | {vbptr} 1> 8 | subLeft_ 1> | <alignment member> (size=4) 1> +--- 1> +--- (virtual base Base) 1>16 | {vfptr} 1>24 | base_ 1> | <alignment member> (size=4) 1> +--- 1>class Diamond size(56): 1> +--- 1> 0 | +--- (base class SubLeft) 1> 0 | | {vbptr} 1> 8 | | subLeft_ 1> | | <alignment member> (size=4) 1> | +--- 1>16 | +--- (base class SubRight) 1>16 | | {vbptr} 1>24 | | subRight_ 1> | | <alignment member> (size=4) 1> | +--- 1>32 | diamond_ 1> | <alignment member> (size=4) 1> +--- 1> +--- (virtual base Base) 1>40 | {vfptr} 1>48 | base_ 1> | <alignment member> (size=4) 1> +--- 1>Diamond::$vbtable@SubLeft@: 1> 0 | 0 1> 1 | 40 (Diamondd(SubLeft+0)Base) 1>Diamond::$vbtable@SubRight@: 1> 0 | 0 1> 1 | 24 (Diamondd(SubRight+0)Base) 1>Diamond::$vftable@: 1> | -40 1> 0 | &Diamond::{dtor} 1> 1 | &Diamond::func 1>Diamond::func this adjustor: 40 1>Diamond::{dtor} this adjustor: 40 1>Diamond::__delDtor this adjustor: 40 1>Diamond::__vecDelDtor this adjustor: 40 1>vbi: class offset o.vbptr o.vbte fVtorDisp 1> Base 40 0 4 0 |
运行输出
1 2 3 4 5 | sizeof Base: 16 sizeof SubLeft: 32 sizeof Diamond: 56 base_ offset: 48 subLeft_ offset: 8 |
refer to: https://blog.csdn.net/oracleot/article/details/5123657