Heim  >  Fragen und Antworten  >  Hauptteil

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 又影响了大小呢?

天蓬老师天蓬老师2713 Tage vor921

Antworte allen(1)Ich werde antworten

  • 迷茫

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

    alignas用在类型声明的时候,会影响类型内部的padding,这部分padding也算类型的大小。会影响sizeof。

    alignas用在变量声明的时候,只是要求运行时为这个变量的地址做相应的对齐。不影响sizeof。

    Antwort
    0
  • StornierenAntwort