对象内存布局 (14)
前篇:http://blog.****.net/pathuang68/archive/2009/04/24/4105810.aspx
继续探讨虚基类对对象内存布局的影响。几个类的继承关系如下图,这是虚基类最为常见的用法之一:
代码如下:
#include <iostream>
using namespace std;
class Base
{
public:
int base_member;
};
class Derived1 : public virtual Base
{
public:
int derived1_member;
};
class Derived2 : public virtual Base
{
public:
int derived2_member;
};
class ChildDerived : public Derived1, public Derived2
{
public:
int childderived_member;
};
int main(void)
{
ChildDerived cd;
cout << "sizeof(Base) = /t/t" << sizeof(Base) << endl;
cout << "sizeof(Derived1) = /t" << sizeof(Derived1) << endl;
cout << "sizeof(Derived2) = /t" << sizeof(Derived2) << endl;
cout << "sizeof(ChildDerived) = /t" << sizeof(ChildDerived) << endl;
cout << endl;
cout << "Derived1 subobject's vbptr = " << (unsigned long*)&cd << endl;
cout << "Derived2 subobject's vbptr = " << (unsigned long*)&cd + 2 << endl;
cout << endl;
cout << "Address of virtual base class table of Derived1 object = " << (unsigned long*)(*((unsigned long*)&cd)) << endl;
cout << "Item 1 in Derived1's virtual base class table = " << *((unsigned long*)*(unsigned long*)(&cd) + 0) << endl;
cout << "Item 2 in Derived1's virtual base class table = " << *((unsigned long*)*(unsigned long*)(&cd) + 1) << endl;
cout << "Item 3 in Derived1's virtual base class table = " << *((unsigned long*)*(unsigned long*)(&cd) + 2) << endl;
cout << endl;
cout << "Address of virtual base class table of Derived2 object = " << (unsigned long*)*((unsigned long*)&cd + 2) << endl;
cout << "Item 1 in Derived2's virtual base class table = " << *((unsigned long*)*((unsigned long*)&cd + 2) + 0) << endl;
cout << "Item 2 in Derived2's virtual base class table = " << *((unsigned long*)*((unsigned long*)&cd + 2) + 1) << endl;
cout << "Item 3 in Derived2's virtual base class table = " << *((unsigned long*)*((unsigned long*)&cd + 2) + 2) << endl;
cout << endl;
cout << "The address of base class Derived1's instance = " << (Derived1*)&cd << endl;
cout << "The address of base class Derived2's instance = " << (Derived2*)&cd << endl;
cout << "The address of base class Base's instance = /t" << (Base*)&cd << endl;
return 0;
}
运行结果如下:
sizeof(Base) = 4 bytes,这个是很好解释的,因为Base中由一个类型为int的成员变量。
sizeof(Derived1) = 12 bytes和sizeofDerived2) = 12 bytes,图解如下:
两个“?”到底是多少我们且不去管它,等我们讨论ChildDerived对象的memory layout时再进行详细说明。从上图可以看到,Base subobject在最后。
现在我们来看看ChildDerived对象的memory layout的情况:
由于Derived1和Derived2都是从Base虚拟继承而来,因而Base是它们的虚基类,编译器在编译的时候会分别给他们安插vbptr指针;Derived1和Derived2同时被ChildDerived普通继承(非虚继承),根据C++标准的要求,基类在在派生类中保证其原始的完整性,因此两个vbptr被继承到了ChildDerived类;由于Base被虚继承,可以看到Base suboject只有一份拷贝,而且放在最后。
从下面图解可以很清楚地发现:
sizeof(ChildDerived) = 24 bytes;
虚基类实例地址(0x0012FF7C) = Derived1的vbptr (0x0012FF68) + Derived1的vbptr到虚基类实例地址的偏移量(24);
虚基类实例地址(0x0012FF7C) = Derived2的vbptr (0x0012FF70) + Derived1的vbptr到虚基类实例地址的偏移量(12)
后篇:http://blog.****.net/pathuang68/archive/2009/04/24/4105902.aspx