【发布时间】:2024-05-02 11:55:01
【问题描述】:
我在 C++ 中使用位字段测试结构的行为,但遇到了一些令人困惑的问题。我的操作系统是 Windows 10 x64。
我使用的代码如下:
struct BitFieldTest
{
bool flag1 : 1;
bool flag2 : 1;
bool flag3 : 1;
bool flag4 : 1;
unsigned char counter1 : 4;
unsigned int counter2 : 4;
};
struct NormalFieldTest
{
bool flag1;
bool flag2;
bool flag3;
bool flag4;
unsigned char counter1;
unsigned int counter2;
};
struct NormalFieldTest2
{
bool flag1;
bool flag2;
bool flag3;
bool flag4;
unsigned char counter1;
};
int main()
{
std::cout << "Size of bool: " << sizeof(bool) << std::endl;
std::cout << "Size of unsigned char: " << sizeof(unsigned char) << std::endl;
std::cout << "Size of unsigned int: " << sizeof(unsigned int) << std::endl;
std::cout << "Size of struct with bit field: " << sizeof(BitFieldTest) << std::endl;
std::cout << "Size of struct without bit field: " << sizeof(NormalFieldTest) << std::endl;
std::cout << "Size of struct without bit field: " << sizeof(NormalFieldTest2) << std::endl;
return 0;
}
输出是:
Size of bool: 1
Size of unsigned char: 1
Size of unsigned int: 4
Size of struct with bit field: 8
Size of struct without bit field: 12
Size of struct without bit field 2: 5
我不明白为什么结构的大小是这样的。任何人都可以解释或分享有关该主题的一些链接吗?
【问题讨论】:
-
"...位域的以下属性是实现定义的...":"关于实际分配的一切类对象中位域的详细信息” source en.cppreference.com/w/cpp/language/bit_field
-
结构被填充为一个可被 4 整除的地址。这种方式访问这些数据比拥有任意地址要快。
标签: c++ alignment sizeof bit-fields