Class member attribute memory

This is what i learned from the book Game Engine Architecure.

 Let's see an example first:


class A{

private:
float f;
bool b1;
double d;
bool b2;
};

One instance of this class take 24 bytes memory, not 4 + 1 + 8 + 1 = 14


The answer is:

An object with one-byte alignment resides at any memory address.

An object with two-byte alignment resides only at even addresses (i.e.,
addresses whose least signifi cant nibble is 0x0, 0x2, 0x4, 0x8, 0xA, 0xC,
or 0xE).
An object with four-byte alignment resides only at addresses that are a
multiple of four (i.e., addresses whose least signifi cant nibble is 0x0, 0x4,
0x8, or 0xC).
 A 16-byte aligned object resides only at addresses that are a multiple of

16 (i.e., addresses whose least signifi cant nibble is 0x0).


The alignment of a structure as a whole is equal to the largest alignment
requirement among its members, in our case, it's double , it's 8 bytes.

Which whem memory allocate is needed, compiler always allocate 8 bytes, 

no matter is bool or double.


So the memory allocate sequence will be:

1.compile found out largest alignment required is 8 byts

2. allocate 8 bytes for float f, which leaves a 4 bytes hole

3. bool b can be put any where, so compiler put it in the hole

4. allocate 8 bytes for doubld d

5. allocate 8 bytes for bool b2, which leaves a 7 bytes hole

So 8 + 8 + 8 = 24,  10 bytes is wasted.  


To avoid this, i should always declare member attribute by descending of attribute size





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值