Home  >  Q&A  >  body text

c++ - alignas会影响sizeof吗

#include <iostream>

using namespace std;
struct alignas(32) S{
    char a;
};

char alignas(4) arr[3];

int main()
{
    cout << sizeof(S) << endl; //output 32
    cout << sizeof(arr) << endl;//output 3
    
    return 0;
}

为什么数组的输出是3呢?为什么这里的alignas没有影响sizeof,而对struct 又影响了大小呢?

天蓬老师天蓬老师2762 days ago951

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 15:41:12

    When

    alignas is used in type declaration, it will affect the padding inside the type, and this part of padding is also counted as the size of the type. Will affect sizeof.

    When

    alignas is used in variable declaration , it only requires the runtime to align the address of this variable accordingly. Does not affect sizeof.

    reply
    0
  • Cancelreply