C ++ - 定义1位Bools

时间:2014-05-23 01:17:56

标签: c++ bit-fields

定义结构的后果如下:

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位,我可以看到它们在内存中按预期工作。当看到VS2010内存窗口时,“SomeOtherData”字符似乎是内存中结构的第二个字节。这就是好的。

但是,我能否可靠地假设这些位中的每一位总是只占用1位?如果我将2个字节记忆到这个结构中,那么第二个字节是否总能可靠地占据我结构中的“SomeOtherData”char元素?

1 个答案:

答案 0 :(得分:4)

结构打包始终与编译器有关,但大多数编译器应将其放在两个字节中。

您可以依赖sizeof(MyStructure)作为数据结构的总大小(考虑到此处讨论的填充Why isn't sizeof for a struct equal to the sum of sizeof of each member?),offsetof(Char16Bits,SomeOtherData)SomeOtherData的正确偏移量}。

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

相关问题