结构末尾未命名位域的用途是什么

What's the purpose of unnamed bit field at the end of structure

我正在学习C,在C Primer Plus中看到一个位域例子如下:

struct box_props {
    bool opaque               : 1;
    unsigned int fill_color   : 3;
    unsigned int              : 4;
    bool show_border          : 1;
    unsigned int border_color : 3;
    unsigned int border_style : 2;
    unsigned int              : 2;
};

我知道中间的4位未命名位域是用来让后面的位从一个新字节开始的。但是,我不明白为什么在结构的末尾还有另一个未命名的位域。它的目的是什么?有必要吗?

What's the purpose of it? Is it necessary?

用于填充。您可以将其视为无法引用的匿名成员。

它是可选的,完全取决于您的布局要求。

Is it necessary?

不,它是可选的。

What's the purpose of it?

这是标准在 §9.6.2 中的说法,C++11(草案 N3337,强调我的):

A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. — end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.

所以这是对编译器的一个提示,将 struct 的所有成员相加得到 2 个八位字节,因此希望编译器能够使 struct 2 个八位字节长。但是,根据标准,没有这样的要求。这是前一点 §9.6.1 的摘录:

extra bits are used as padding bits and do not participate in the value representation of the bit-field. Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.

因此,对于使用位域的 struct/class 的大小或对齐,标准不提供任何进一步的保证。