为什么类对象的大小基于成员的顺序不同? [英] Why is the size of a class object different based on order of members?
本文介绍了为什么类对象的大小基于成员的顺序不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
}
如果有人知道,请让我知道为什么喜欢这个。
感谢
Hara
If any one knows, Please let me know why like this. Thanks Hara
推荐答案
由于对齐。 x86编译器倾向于在4字节边界上对齐int类型(用于更快的内存访问),因此CHaraICICCC可能会被布局为:
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
总共15个字节,而CHaraIICCCC将是:
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
总共12个字节(没有字节浪费填充)。当然,这是很多编译器相关的,取决于你的编译选项。
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.
这篇关于为什么类对象的大小基于成员的顺序不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文