Inside the C++ Object Model - 3. The Semantics of Data

A char will be inserted into a class object if it is empty - 1 byte for an empty class object

class X {};
class Y: public virtual X {};
class Z: public virtual X {};
class A: public Y, public Z {}

The size of Y and Z are decided by:

  1. overhead of the language - a pointer is created in derived class object and points to virtual base class subobject
  2. optimization done by compiler - some new compiler will not insert the 1 byte for virtual base class subobject
  3. memory alignment

X: 1 byte + Y: pointer which points to virtual base class subobject 4 bytes + memory alignment 3 bytes = 8 bytes

static data members are stored in data segment of the program. 

Read/Write of Data Member

static data member is not stored in class object, so following situations have the same behaviour and performance. 

// chunkSize is static data member 
origin.chunkSize = 250; 
pt->chunkSize = 250; // will be converted to origin.chunkSize = 250 inside by compiler

this pointer (implicit class object) is used by member function to access nonstatic data member of class object.

to access nonstatic data member - compiler takes start address of class object and add an offset onto it. 

origin._y = 0.0;
// will be converted to 
&origin + (&Point3d::_y-1); // the offset value of points which point to data member is always +1

If the class is a derived class object and there is at least one virtual base class, and the data member is from virtual base class. Then an additional link is needed to get the exact offset value of data member (compiler does not know the exact offset value when compiling). 

origin.x = 0.0;
pt->x = 0.0;

Concrete inheritance will not induce additional space or time consuming, just like C struct. 

notice padding - padding exists in every single class object. 

For those virtual functions, additional cost is from:

  1. a virtual function table
  2. a vptr which points to virtual function table
  3. expanding constructor - initialize vptr in all derived class object or base class object
  4. expanding destructor

For virtual inheritance:

if a class object has more than one virtual base class subobjects, it will be divided into shared zone and consistent zone

additional cost:

  • pointers will be saved in derived class object and point to each virtual base class subobject
  • or Microsoft compiler will create a virtual base class table
  • or offset value of virtual base class is stored in virtual function table

Virtual inheritance will impact the optimization ability of compiler by those indirect linking.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值