C++ - Defining 1 Bit Bools

C++ - Defining 1 Bit Bools

本文关键字:Bit Bools Defining C++      更新时间:2023-10-16

这样定义结构体的结果是什么?

typedef struct {
    bool          Bit0 : 1;    //Bit 0
    bool          Bit1 : 1;
    bool          Bit2 : 1;
    bool          Bit3 : 1;
    bool          Bit4 : 1;
    bool          Bit5 : 1;
    bool          Bit6 : 1;
    bool          Bit7 : 1;     //Bit 7
    char          SomeOtherData;
}Char16Bits;
...
Char16Bits MyStructure;
MyStructure.Bit0 = true;
MyStructure.Bit1 = false;

在我的测试程序中,一切似乎都很好,每个"Bit0-7"只占用1位,我可以看到它们在内存中按预期工作。"SomeOtherData"字符似乎是在查看VS2010内存窗口时内存结构的第二个字节,这一切都很好。

然而,我能可靠地假设这些位总是只占用1位吗?如果我记忆2个字节到这个结构中,第二个字节是否总是可靠地占据我的结构中的"SomeOtherData"字符元素?

结构打包总是与编译器相关,但大多数编译器应该将其放在两个字节内。

可以依赖sizeof(MyStructure)作为数据结构的总大小(考虑到此处讨论的填充,为什么结构的n't sizeof等于每个成员的sizeof的总和?),offsetof(Char16Bits,SomeOtherData)SomeOtherData的正确偏移量。

如果您需要编写假设特定大小或偏移量的代码,请使用assert()static_assert(),以便代码不允许在不遵循您的假设的平台上运行。