c++ - 具有 4 个 6 位成员的结构的 sizeof

标签 c++ struct bit sizeof

<分区>

为什么是这段代码:

#include <iostream>
struct S {
    unsigned char a:6, b:6, c:6, d:6;
};
    int main(int argc, char *argv[]) {
    std::cout << sizeof(S);
    return 0;
}

返回 4?它的大小不应该是 4 x 6 = 24b = 3B 吗?相反,这段代码:

struct S { unsigned char a:4, b:4, c:4, d:4; };

返回一个 2,而这个:

struct S { unsigned char a:4, b:4, c:4, d:4, e:4, f:4; };

返回一个 3...

最佳答案

来自 CppReference: Bit Fields :

The following properties of bit fields are implementation-defined:

  • [...]
  • Everything about the actual allocation details of bit fields within the class object

    • For example, on some platforms, bit fields don't straddle bytes, on others they do

是的,它是实现定义的(即由编译器决定)。

So, even though the compiler calculates the other 2 without padding, it adds padding the first one?

是的,因为在第一种情况下,如果不填充,值将“跨越”字节边界,而在其他两个示例中,它们不会。

同样,这是实现定义的,可以在另一个平台、同一平台上的不同编译器甚至同一编译器的不同版本上以不同方式处理。

关于c++ - 具有 4 个 6 位成员的结构的 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47224626/

相关文章:

c - 返回指向局部结构的指针

arrays - 在go中创建异构json数组

algorithm - 我如何理解此代码挑战中此测试用例的结果?

c++ - 使用自定义删除器为 unique_ptr 返回 nullptr 失败

c++ - 为什么引用数组是非法的?

c++ - QuantLib 入门指南

c - ANSI C/C89 结构体到 int array[]

java - 移位后的位值

统计二进制文件中 32 位数字的个数

c++ - 无法将 WSPStartup 设置为 dll 导出