内存对齐的大小是多少?
按照吉良吉影所说:
此外还有编译器的默认对齐值,一般默认对齐值为4(结构体的实际对齐值会取结构体对齐值和编译器默认对齐值中较小的那一个)。
只要没设置,一般是4了。
内存对齐的规律到底是什么?
看了知乎专栏,微软页面等各种文章,其实他们总结的规律都难以背诵。在我看来,变量对齐的应当遵循这一条原则:
尽量避免变量本可以放在一个word中,却被分割放到两个word里,使得读取变量时要多读一个word。
举个例子:
- 设一个word是4字节,一个double占8字节,就应当放在两个word里面,而不应该放到三个
- 设一个int是4字节,就应当放到1个而非分割到2个word里面。
#include <iostream>
using namespace std;
struct Pin {
int x;
char y;
short z;
};
struct Foo {
int x;
char y;
char z;
};
struct Bar{
int x;
char y;
char z;
char c1;
char c2;
};
int main()
{
cout << "Pin" << endl;
cout << sizeof(int) << " " << sizeof(char) << " " << endl;
cout << alignof(Pin) << " " << sizeof(Pin) << endl;
cout << "Foo" << endl;
cout << sizeof(int) << " " << sizeof(char) << " " << endl;
cout << alignof(Foo) << " " << sizeof(Foo) << endl;
cout << "Bar" << endl;
cout << sizeof(int) << " " << sizeof(char) << " " << endl;
cout << alignof(Bar) << " " << sizeof(Bar) << endl;
return 0;
}
输出结果发现,三种结构体占用内存相等。因为三种结构体x成员之后的成员,比如y、z等,都不需要分割放到两个word中,可以码在一个word里。
alignof
的作用? 如cppreference所说,alignof
会输出对应类型的对齐字节数(是对齐方式,不是指结构大小)。