C++11 内存对齐 alignof alignas max_align_t
alignof( type-id ) 查询类型的对齐要求,以字节为单位 struct Storage { char a; int b; double c; long long d; }; // struct alignas(alignof(long double)) AlignasStorage { // struct alignas(long double) AlignasStorage { struct alignas(std::max_align_t) AlignasStorage { // max_align_t 相当于 alignof(long double) 内存对齐为 16 字节 // 这三种写法都可以 char a; int b; double c; long long d; }; struct Empty {}; struct alignas(64) Empty64 {}; int main() { std::cout << alignof(Storage) << std::endl; // 8 std::cout << sizeof(Storage) << std::endl; // 24 内存对齐为 8 字节,所以大小为 8 的整数倍 std::cout << alignof(AlignasStorage) << std::endl; // 16 std::cout << sizeof(AlignasStorage) << std::endl; // 32 内存对齐为 16 字节,所以大小为 16 的整数倍 int a = 10; int &b = a; std::cout << alignof(b) << std::endl; // 4 引用类型返回引用类型的对齐要求 int x[10]; std::cout << alignof(x) << std::endl; // 4 数组类型返回元素类型的对齐要求 std::cout << "Alignment of" "\n" "- char : " << alignof(char) << "\n" // 1 "- pointer : " << alignof(int*) << "\n" // 8 "- int : " << alignof(int) << "\n" // 4 "- long long : " << alignof(long long) << "\n" // 8 "- empty class : " << alignof(Empty) << "\n" // 1 "- alignas(64) Empty: " << alignof(Empty64) << "\n"; // 64 return 0; }