Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-定义1位布尔_C++_Bit Fields - Fatal编程技术网

C++ C++;-定义1位布尔

C++ C++;-定义1位布尔,c++,bit-fields,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

按如下方式定义结构的后果是什么:

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


然而,我能可靠地假设这些位中的每一位总是只占用1位吗?如果我将2个字节存储到这个结构中,那么第2个字节是否总是可靠地占据我的结构中的“SomeOtherData”字符元素?

结构打包总是依赖于编译器,但大多数编译器应该将其放在两个字节中

您可以依赖于
sizeof(MyStructure)
是数据结构的总大小(考虑此处讨论的填充),而
offsetof(char16位,SomeOtherData)
SomeOtherData
的正确偏移量


如果您需要编写假定特定大小或偏移量的代码,请使用
assert()
static\u assert()
,这样代码就不允许在不符合您假设的平台上运行。

结构打包始终依赖于编译器,但大多数编译器应该将其放入两个字节

您可以依赖于
sizeof(MyStructure)
是数据结构的总大小(考虑此处讨论的填充),而
offsetof(char16位,SomeOtherData)
SomeOtherData
的正确偏移量


如果您需要编写假定特定大小或偏移量的代码,请使用
assert()
static\u assert()
,这样代码就不允许在不符合您假设的平台上运行。

您是否尝试过检查大小(char16位)?您可以使用
offset of
Bit0
Bit7
中的任何一个都不能通过两个或多个线程与同一
Char16Bits
对象中的另一个同时修改。对于普通的
bool
字段,这不是问题。您是否尝试过检查sizeof(char16位)?您可以
static\u assert
使用
offsetof
@Bryan Chen,那么您是否建议在编译器创建超过16位的结构时抛出错误?@phyrrus9,sizeof并不总是有效的,因为有时会根据您声明的内容向结构的末尾添加额外的字节。一个结果是,
Bit0
Bit7
中的任何一个都不能通过两个或多个线程与同一
Char16Bits
对象中的另一个同时修改。对于普通的
bool
字段,这不是问题。谢谢你的回答,我也这么怀疑。另一个问题是,一旦编译了应用程序,是否有可能改变结构的大小?也就是说,如果它在我的电脑上编译并运行良好,那么同一可执行文件是否有可能在另一台电脑上以不同的方式分配结构(假设您使用的是完全相同的可执行文件)?不,结构的大小在编译时确定。谢谢heaps@Russell Borogrove!这正好回答了我的问题:)谢谢你的回答,我也这么怀疑。另一个问题是,一旦编译了应用程序,是否有可能改变结构的大小?也就是说,如果它在我的电脑上编译并运行良好,那么同一可执行文件是否有可能在另一台电脑上以不同的方式分配结构(假设您使用的是完全相同的可执行文件)?不,结构的大小在编译时确定。谢谢heaps@Russell Borogrove!这正好回答了我的问题:)