为什么结构的 sizeof 不等于每个成员的 sizeof 之和? [英] Why isn't sizeof for a struct equal to the sum of sizeof of each member?

查看:40
本文介绍了为什么结构的 sizeof 不等于每个成员的 sizeof 之和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 sizeof 运算符返回的结构大小大于结构成员的总大小?

Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?

推荐答案

这是因为添加了填充来满足对齐约束.数据结构对齐影响程序的性能和正确性:

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:

  • 未对齐的访问可能是一个硬错误(通常是SIGBUS).
  • 未对齐的访问可能是软错误.
    • 在硬件中进行更正,以适度降低性能.
    • 或者通过在软件中模拟来纠正严重的性能下降.
    • 此外,原子性和其他并发性保证可能会被破坏,从而导致细微的错误.

    以下是使用 x86 处理器(均使用 32 位和 64 位模式)的典型设置的示例:

    Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):

    struct X
    {
        short s; /* 2 bytes */
                 /* 2 padding bytes */
        int   i; /* 4 bytes */
        char  c; /* 1 byte */
                 /* 3 padding bytes */
    };
    
    struct Y
    {
        int   i; /* 4 bytes */
        char  c; /* 1 byte */
                 /* 1 padding byte */
        short s; /* 2 bytes */
    };
    
    struct Z
    {
        int   i; /* 4 bytes */
        short s; /* 2 bytes */
        char  c; /* 1 byte */
                 /* 1 padding byte */
    };
    
    const int sizeX = sizeof(struct X); /* = 12 */
    const int sizeY = sizeof(struct Y); /* = 8 */
    const int sizeZ = sizeof(struct Z); /* = 8 */
    

    可以通过按对齐对成员进行排序来最小化结构的大小(按大小排序对于基本类型就足够了)(如上例中的结构 Z).

    One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z in the example above).

    重要说明:C 和 C++ 标准都声明结构对齐是实现定义的.因此,每个编译器可能会选择不同地对齐数据,从而导致不同且不兼容的数据布局.因此,在处理将由不同编译器使用的库时,了解编译器如何对齐数据非常重要.某些编译器具有命令行设置和/或特殊的 #pragma 语句来更改结构对齐设置.

    IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma statements to change the structure alignment settings.

    这篇关于为什么结构的 sizeof 不等于每个成员的 sizeof 之和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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