结构的尺寸已经无符号短整型

结构的尺寸已经无符号短整型

问题描述:

我是冲浪在我们的组织数据文件之一,我碰到下面这段code的来了。

I was surfing in one of our organisational data documents and I came across the following piece of code.

struct A {
 unsigned short int i:1;
 unsigned short int j:1;
 unsigned short int k:14;
};


int main(){
 A aa;
 int n = sizeof(aa);
 cout << n;
}

起初我以为大小将是6个字节的无符号短整型的大小为2个字节。但上述code的输出为2个字节(在Visual Studio 2008中)。

Initially I thought the size will be 6 bytes as the size of the unsigned short int is 2 bytes. but the output of the above code was 2 bytes(On visual studio 2008).

时有轻微的可能性,即 I:1 记者:1 K:14 使得它的位域还是什么?它只是一个猜测,我不是很肯定它。有人可以帮我在这?

Is there a slight possibility that the i:1, j:1 and k:14 makes it a bit field or something? Its just a guess and I am not very sure about it. Can somebody please help me in this?

没错,这就是位域,确实如此。

Yes, this is bitfield, indeed.

嗯,我不是很肯定 C ++ ,但线 C99 标准,按章6.7.2.1(10):

Well, i'm not very much sure about c++, but In c99 standard, as per chapter 6.7.2.1 (10):

这是实现可分配任何可寻址存储单元,大到足以容纳一个位字段。如果有足够的空间保持,紧跟在一个结构的另一位字段位字段须包装到同一单元的相邻比特。如果没有足够的空间仍然存在,不适合一个位字段是否被放入下一个位或重叠相邻的单元是实现定义的。一个单位(高位到低位或低阶到高阶)内的位域的分配顺序是实现定义。可寻址存储单元的取向是不确定的。

An implementation may allocate any addressable storage unit large enough to hold a bit-field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next bits or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.

这使你的结构尺寸(1位+ 1位+ 14位)= 16位= 2字节。

That makes your structure size (1 bit + 1 bit + 14 bits) = 16 bits = 2 bytes.

注意:无结构填充在这里被认为

Note: No structure padding is considered here.

编辑:

C ++ 14 标准,章§9.7,

形式的成员声明符

标识符选择属性 - 符-SEQ 选择:恒恩pression结果

identifieropt attribute-specifier-seqopt: constant-expression

指定位字段;它的长度是从位字段名称由冒号掀起。 [...]一类对象中的位域的分配
  实现定义。位字段的对齐是实现定义的。位字段被打包成一些可寻址的分配单元。

specifies a bit-field; its length is set off from the bit-field name by a colon. [...] 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.