zoukankan      html  css  js  c++  java
  • [C++关键字] alignof & alignas 内存对齐 sizeof 占内存大小

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

    #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) << '
    '
        << "alignment of pointer : "    << alignof(int*)  << '
    '
        << "alignment of char : "       << alignof(char)  << '
    '
        << "alignment of Foo : "        << alignof(Foo)   << '
    '
        << "Size of Foo: " << sizeof(Foo) << '
    '
        << "alignment of FooNew : "        << alignof(FooNew)   << '
    ';
    }

    输出结果是:

    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

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

  • 相关阅读:
    路径问题
    移动端推荐使用
    js获取各种宽高方法
    html 符号大全
    bzoj4923 K小值查询
    bzoj3781 小B的询问
    bzoj1799 [Ahoi2009]self 同类分布
    bzoj2005 [Noi2010]能量采集
    bzoj4039 集会
    bzoj2516 电梯
  • 原文地址:https://www.cnblogs.com/littletail/p/5274349.html
Copyright © 2011-2022 走看看