直接上代码测试是入门神器,以结构体为例,解释“对齐”和“补齐”概念。
#include <iostream>
struct Empty {};
struct Foo {
int f2;
double f1;
char c;
};
struct alignas(16) FooNew
{
int f2;
double f1;
char c;
};
int main()
{
std::cout << "alignment of empty class: " << alignof(Empty) << '\n'
<< "alignment of pointer : " << alignof(int*) << '\n'
<< "alignment of char : " << alignof(char) << '\n'
<< "alignment of Foo : " << alignof(Foo) << '\n'
<< "Size of Foo: " << sizeof(Foo) << '\n'
<< "alignment of FooNew : " << alignof(FooNew) << '\n';
}
输出结果是:
alignment of empty class: 1
alignment of pointer : 8
alignment of char : 1
alignment of Foo : 8
Size of Foo: 24
alignment of FooNew : 16
总之,对齐是某种类型的初始位置在内存上的限定,补齐是对该类型大小的限定,两者共同组成了该类型在内存上的排布规则,提高操作效率。
原文链接: https://www.cnblogs.com/littletail/p/5274349.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/230199
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!