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