c++ - 维基上的这个位域的sizeof?

查看:78
本文介绍了c++ - 维基上的这个位域的sizeof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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.[...]

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

这篇关于c++ - 维基上的这个位域的sizeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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