首页 > 编程语言 > 详细

[C++关键字] alignof & alignas 内存对齐

时间:2016-03-14 01:34:13      阅读:177      评论:0      收藏:0      [点我收藏+]

直接上代码测试是入门神器,以结构体为例,解释“对齐”和“补齐”概念。

#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

总之,对齐是某种类型的初始位置在内存上的限定,补齐是对该类型大小的限定,两者共同组成了该类型在内存上的排布规则,提高操作效率。

[C++关键字] alignof & alignas 内存对齐

原文:http://www.cnblogs.com/littletail/p/5274349.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!