具有 4 个 6 位成员的结构的 sizeof
sizeof a struct with 4 6-bit members
为什么是这个代码:
#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; };
returns一个2,而这个:
struct S { unsigned char a:4, b:4, c:4, d:4, e:4, f:4; };
returns 一个 3...
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?
是的,因为在第一种情况下,如果不填充,值将 "straddle" 字节边界,而在其他两个示例中,它们不会。
同样,这是实现定义的,可以在另一个平台、同一平台上的不同编译器甚至同一编译器的不同 版本 上以不同方式处理。
为什么是这个代码:
#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; };
returns一个2,而这个:
struct S { unsigned char a:4, b:4, c:4, d:4, e:4, f:4; };
returns 一个 3...
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?
是的,因为在第一种情况下,如果不填充,值将 "straddle" 字节边界,而在其他两个示例中,它们不会。
同样,这是实现定义的,可以在另一个平台、同一平台上的不同编译器甚至同一编译器的不同 版本 上以不同方式处理。