Why is the size of a class object different based

2019-02-18 10:39发布

class CHaraICICCC
{
int i;
char c1;
int j;
char c2;
char c3;
char c4;
};

class CHaraIICCCC
{
int i;
int j;
char c1;
char c2;
char c3;
char c4;
};

void fun()
{
    CHaraICICCC eici;
    CHaraIICCCC eiicc;

    int icic = sizeof(eici); // -> output of icic is 16.
    int iicc = sizeof(eiicc); // -> output of icic is 12.
}

If any one knows, Please let me know why like this. Thanks Hara

标签: c++ class sizeof
3条回答
Lonely孤独者°
2楼-- · 2019-02-18 11:33

Because of alignment. x86 compilers tend to align int types on 4 bytes boundary (for faster memory access) so CHaraICICCC would probably be laid out as this:

byte  0: \
byte  1: | <--- int i
byte  2: |
byte  3: /  
byte  4: <----- char c1
byte  5: \
byte  6: | <--- Padding (wasted bytes)
byte  7: / 
byte  8: \
byte  9: | <--- int j  
byte 10: |
byte 11: /
byte 12: <----- char c2
byte 13: <----- char c3
byte 14: <----- char c4

for a total of 15 bytes, while CHaraIICCCC would be:

byte  0: \
byte  1: | <--- int i
byte  2: |
byte  3: /  
byte  4: \
byte  5: | <--- int j 
byte  6: |
byte  7: /
byte  8: <----- char c1
byte  9: <----- char c2
byte 10: <----- char c3
byte 11: <----- char c4

for a total of 12 bytes (with no bytes wasted for padding). Of course, this is much compiler-related and dependant on your compilation options.

查看更多
够拽才男人
3楼-- · 2019-02-18 11:35

Stretching the question of "why" a little, I think I read somewhere that the reason for alignment is that it lets the CPU ignore bits of the data -- if your data is known to be 8-byte aligned, for example, the CPU can just ignore the 3 lower bits of the address, which improves efficiency. I could be wrong, but if I remember correctly, that's why CPUs require or prefer alignment.

查看更多
Evening l夕情丶
4楼-- · 2019-02-18 11:43

With the default pack mode, on most architectures, members will be aligned at an offset (from the start of the structure) which is a multiple of their size.

If neccessary, padding bytes will be added to the structure to obtain that alignment.

So, assuming default packing and 4-byte integers, your first structure is really like this:

class CHaraICICCC
{
    int i;
    char c1;
    char padding[3];
    int j;
    char c2;
    char c3;
    char c4;
};
查看更多
登录 后发表回答