首页 > 开发 > C++ > 正文

维基上的这个位域的sizeof?

2017-09-11 21:19:17  来源: 网友分享
struct box_props{    unsigned int opaque : 1;    unsigned int fill_color : 3;    unsigned int : 4; // fill to 8 bits    unsigned int show_border : 1;    unsigned int border_color : 3;    unsigned int border_style : 2;    unsigned char : 0; // fill to nearest byte (16 bits)    unsigned char width : 4, // Split a byte into 2 fields of 4 bits        height : 4;};int main() {    std::cout << sizeof(box_props);}

环境: x86平台, msvc 输出:

8

大家能根据这个例子帮我分析下为什么是8吗?

解决方案

你的unsigned int应该是四个字节。unsigned char : 0这里开始下一个分配单元,后面两个unsigned char一共占一个字节。

所以这个位域,前半部分unsigned int占4个,后半部分unsigned char占一个,随后三个字节的padding。最后一共就是八个字节。

标准约定这是平台相关的:

9.6.1 [...]Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined.[...]

参照微软文档关于位域的描述