c++中的结构对齐和填充
Structure Alignment and padding in c++
代码的输出是如何变化的?我知道
struct-declarator:
declarator
type-specifier declarator opt : constant-expression
这里的constant-expression以位为单位指定字段的宽度。
#include<stdio.h>
int main()
{
struct value{
int bit1 : 8;
int bit3 : 8;
int bit4 : 8;
}bit;
printf("%dn",sizeof(bit));
return 0;
}
输出为4
#include<stdio.h>
int main()
{
struct value{
int bit1 : 1;
int bit3 : 4;
int bit4 : 4;
}bit;
printf("%dn",sizeof(bit));
return 0;
}
输出4 #include<stdio.h>
int main()
{
struct value{
int bit1 : 1;
int bit3 : 16;
int bit4 : 16;
}bit;
printf("%dn",sizeof(bit));
return 0;
}
输出为8
据我所知,结构体的大小是它内部声明的所有数据类型的大小。
这是由于打包和字节对齐。检查结构对中
查看C-FAQ了解详细信息
是为"对齐"设置的。许多处理器不能访问2字节和4字节的数量(例如int型和long int型),如果它们被塞满了。
假设你有这样的结构:
struct {
char a[3];
short int b;
long int c;
char d[3];
};
现在,你可能认为应该可以像这样将这个结构打包到内存中:
+-------+-------+-------+-------+
| a | b |
+-------+-------+-------+-------+
| b | c |
+-------+-------+-------+-------+
| c | d |
+-------+-------+-------+-------+
但是如果编译器这样安排的话,对处理器来说会容易得多:
+-------+-------+-------+
| a |
+-------+-------+-------+
| b |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d |
+-------+-------+-------+
在packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will
pad "中,结构(好像有额外的,不可见的字段)如下:
+-------+-------+-------+-------+
| a | pad1 |
+-------+-------+-------+-------+
| b | pad2 |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d | pad3 |
+-------+-------+-------+-------+
还可以查看C-Faq
答案是:视情况而定。该标准对位域的布局没有要求。具体地说,
类中位域的分配对象是实现定义的。位字段的对齐由实现定义。位域被打包到某个可寻址的分配单元。[注:位域在某些机器上跨分配单元,而不是。于人。位域在一些机器上从右到左分配,在其他机器上从左到右分配。-end note]
- 假设为32位整数,每个整数的最大空间需求为
3*sizeof(int)
,或12,12,12字节。 - 最大包装的最小尺寸分别是3,3,4字节,这可能取决于
#pragma pack
。 - 典型的结果可能是4,4,8,但这很容易因编译器而异。
所以答案是:看情况而定。这就是我强烈建议不要在布局或大小要求很重要的时候使用位字段的原因之一。
相关文章:
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 哪些值存储在对齐的结构/类对象的填充字节中
- 关于数据对齐和填充的另一个困惑
- 如何创建 std::vector of char/std::byte,其中第一个字节对齐到 16 个字节,但没有填充
- 填充和对齐 - 误解
- 安腾ABI在多大程度上真正指定了填充和对齐
- 结构对齐填充、最大填充大小和结构成员顺序
- blob内部数据的对齐和填充
- C++ GLSL 数据对齐/填充
- Do 4字节对齐的指针使用任何填充
- 为什么堆栈上对齐的整数之间有 8 个字节的"0xcc"填充?C++ 32位视窗7
- c++中的结构对齐和填充
- 简单的结构对齐/填充问题
- 手动填充顶点结构以实现对齐
- 如何在OpenGL中正确填充和对齐std430布局中的数据
- c++.结构在不同平台上的填充/对齐和布局兼容性的自动检查
- 结构/类数据对齐和填充的算法
- 结构件对齐 - 是否可以假设没有填充