Visual C++ 8.0对象布局的奥秘:虚函数、多继承、虚拟继承2010-04-16从MS Visual C++ Team的Andy Rich那里又偷学到一招:VC8的隐含编译项/d1reportSingleClassLayout和/d1reportAllClassLayout 。看个复杂的例子吧(如下),现在假设我们想知道Derived类的对象布局,怎么办? 在Project Properties->C++->Command Line->Additional Options里面加上/d1reportSingleClassLayoutDerived吧!
class CommonBase
{
int co;
};
class Base1: virtual public CommonBase
{
public:
virtual void print1() {}
virtual void print2() {}
private:
int b1;
};
class Base2: virtual public CommonBase
{
public:
virtual void dump1() {}
virtual void dump2() {}
private:
int b2;
};
class Derived: public Base1, public Base2
{
public:
void print2() {}
void dump2() {}
private:
int d;
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
F5编译之,你会惊奇地发现,Output里面有如下字样:
1 class Derived size(32):
2+---
3| +--- (base class Base1)
40 | | {vfptr}
54 | | {vbptr}
68 | | b1
7| +---
8| +--- (base class Base2)
9 12 | | {vfptr}
10 16 | | {vbptr}
11 20 | | b2
12| +---
13 24 | d
14+---
15+--- (virtual base CommonBase)
16 28 | co
17+---
18
19 Derived::$vftable@Base1@:
200 | &Base1::print1
211 | &Derived::print2
22
23 Derived::$vftable@Base2@:
240 | &Base2::dump1
251 | &Derived::dump2
26
27 Derived::$vbtable@Base1@:
280 | -4
291 | 24 (Derivedd(Base1+4)CommonBase)
30
31 Derived::$vbtable@Base2@:
320 | -4
331 | 12 (Derivedd(Base2+4)CommonBase)
34
35 Derived::print2 this adjustor: 0
36 Derived::dump2 this adjustor: 12