什么是无名位字段在结构的端部的目的 [英] What's the purpose of unnamed bit field at the end of structure

查看:170
本文介绍了什么是无名位字段在结构的端部的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C.在的ç的Primer Plus 的,我看到了一个位域举例如下:

 结构box_props {
    布尔不透明:1;
    unsigned int类型fill_color:3;
    无符号整型:4;
    布尔show_border:1;
    unsigned int类型border_color:3;
    unsigned int类型border_style:2;
    无符号整型:2;
};

我明白中间的4位无名位字段用于让下列位在一个新的字节开始。不过,我不明白为什么会出现在结构的末尾另一个无名位字段。什么是它的目的是什么?有必要吗?


解决方案

  

有必要吗?


不,它是可选的。


  

什么是它的目的是什么?


下面就是标准说,在§9.6.2,C ++ 11(N3337草案,重点煤矿):


  

一个用于省略了标识符位域声明声明的未命名位字段。无名位字段不是会员,不能初始化。 [注:未命名位字段是很有用的填充顺应外部强加的布局。 - 注完] 作为一个特殊的情况下,具有零宽度的未命名位字段中指定的分配单元的边界下一个位字段的对齐。声明只有一个无名位字段时,可能会不断-EX pression的价值等于零。


所以这是一个暗示,编译器总结的结构导致2 octects所有成员,从而完成希望编译器将使结构 2 octects长。然而,按照标准有没有这样的规定。下面是从previous点摘录,§9.6.1:


  

额外位被用作填充位,不参与比特字段的值再presentation。在类中位域的分配
  目标是实现定义的。位字段的对齐是实现定义的。位字段被打包成一些可寻址的分配单元。


因此​​,标准没有比这再使用保证任何关于大小或结构 / 类对齐位字段。

I am learning C. In C Primer Plus, I saw an bit field example as follows:

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;
};

I do understand the 4-bit unnamed bit field in the middle is used for letting the following bits start at a new byte. However, I don't understand why there is another unnamed bit field at the end of the structure. What's the purpose of it? Is it necessary?

解决方案

Is it necessary?

Nope, it's optional.

What's the purpose of it?

Here's what the standard says in §9.6.2, C++11 (draft N3337, emphasis mine):

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.

So it's a hint to the compiler that summing up all the members of the struct leads to 2 octects and thus is done hoping the compiler would make the struct 2 octects long. However, as per the standard there's no such requirement. Here's the excerpt from the previous point, §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.

Hence the standard does not guarantee any further than this regarding the size or alignment of a struct/class using bit-fields.

这篇关于什么是无名位字段在结构的端部的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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