Sizeof类如何改变变量的顺序 [英] How does Sizeof class matters on change of order of variable

查看:80
本文介绍了Sizeof类如何改变变量的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Guys,



我不清楚改变变量顺序的班级规模。



见下面的类:它给我20个字节的大小



Hello Guys,

I am not clear with size of class on altering order of variables.

See below class: It gives me size as 20 bytes

class A
{
public:
        int int1;
        int int2;
        int i;
        long l;
        short s;
        char c;



};





然而,如果我改变订单的大小char c(放在课程开始时)





whereas, if I change size of order of char c ( put at the start of class)

class A
{
public:
        char c;
        int int1;
        int int2;
        int i;
        long l;
        short s;
};





现在,我看到班级的大小变为24个字节。

可以你能解释一下吗?





问候,

Joy



Now, I see size of class becomes as 24 bytes.
can you please explain this?


Regards,
Joy

推荐答案

结构的大小取决于成员的对齐方式,这可能受编译器默认设置或显式设置对齐的影响(例如VisualC ++的#pragma pack()http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx [ ^ ])。为了确保添加这种对齐填充(这是未使用的字节占用空间并增加存储结构所需的大小。

填充用于避免对大于a的数据结构的低效访问单字节。



这里有一个例子,由于成员的次优订购造成的尺寸差异显着:



(char是1个字节,长是4个字节,对齐是针对4字节单一访问进行优化的)

The size of a structure is depending on the alignment of the members, this can be influenced by the compiler default settings, or by explicit setting alignment (e.g. #pragma pack() for VisualC++ http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx[^]). To ensure this alignment padding is added (which are unused bytes that take up space and increase the size required to store the structure.
The padding is used to avoid inefficient access to data structures that are larger than a single byte.

Here an example of significant difference in size due to suboptimal ordering of members:

(char is 1 byte, long is 4 bytes and the alignment is optimized for 4 byte single access)
1 byte    char1
3 byte    <padding>
4 byte    long1
1 byte    char2
3 byte    <padding>
4 byte    long2
1 byte    char3
3 byte    <padding>
4 byte    long3
1 byte    char4
3 byte    <padding>
4 byte    long4





整个结构为32字节由于必要的填充将长整齐对齐到下一个4字节边界。



重新排序成员将其减少到20个字节:



The whole structure was 32 bytes due to the necessary padding to align the longs to the next 4 byte boundary.

Reordering the members cut this down to 20 bytes:

4 byte    long1
4 byte    long2
4 byte    long3
4 byte    long4
1 byte    char1
1 byte    char2
1 byte    char3
1 byte    char4


这篇关于Sizeof类如何改变变量的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆