对齐规则:
每个变量相对起始位置的偏移量必须是该变量类型大小的整数倍!{\red{每个变量相对起始位置的偏移量必须是该变量类型大小的整数倍!}}每个变量相对起始位置的偏移量必须是该变量类型大小的整数倍!
对于union,CPU默认按最短成员对齐:
union u{
double a;
int b;
};
union u1{
char a[13];
int b;
};
union u2{
char a[13];
char b;
};
int main(){
cout<<sizeof(u)<<endl;
cout<<sizeof(u1)<<endl;
cout<<sizeof(u2)<<endl;
return 0;
}
输出:{\orange{输出:}}输出: 8 16 13
union成员共享内存,并以最小成员对齐,不足补齐,故union可以用来判断CPU大小端。
对于struct,按规则对齐,最后大小必须是最大成员的整数倍:
struct s{
char c;
short s1;
short s2;
int i;
};
struct s1{
char c;
int i;
};
struct s2{
char c;
short s1;
int i;
};
struct s3{
char c;
int i;
short s1;
};
int main(){
cout<<sizeof(s)<<endl;
cout<<sizeof(s1)<<endl;
cout<<sizeof(s2)<<endl;
cout<<sizeof(s3)<<endl;
return 0;
}
output:{\orange{output:}}output: 12 8 8 12
pragma pack{\red{pragma\ pack}}pragma pack 修改CPU对齐方式
#pragma pack(1)
struct s{
char c;
short s1;
short s2;
int i;
};
struct s1{
char c;
int i;
};
struct s2{
char c;
short s1;
int i;
};
struct s3{
char c;
int i;
short s1;
};
int main(){
cout<<sizeof(s)<<endl;
cout<<sizeof(s1)<<endl;
cout<<sizeof(s2)<<endl;
cout<<sizeof(s3)<<endl;
return 0;
}
Output:{\orange{Output:}}Output: 9 5 7 7
规则:
pragma(n),n必须是1,2,4,8,若不是则按默认
内存对齐的意义:
-
对齐后性能可以提升。
-
方便平台移植