C++/C++

__declspec(align(#)) 과 alignas

Elan 2021. 5. 7. 05:40

__declspec(align(#))

 

MSVC에서 제공하는 예약어를 사용하여 메모리 정렬 단위를 설정할 수 있다.

__declspec(align(#))은 struct, union, class 또는 변수를 정의할 때 사용할 수 있다.

객체 생성 시 메모리를 #바이트로 정렬하라는 의미를 컴파일러에게 전달한다.
( 숫자 # 은 2 ~ 8192 범위이며, 동시에 2^n 승에 해당하는 수를 만족해야한다)

__declspec(align(32)) 
struct Str1{
   int a;//4
   int b;//4
   int c;//4
   int d;//4
   int e;//4
   //padding 12 bytes 추가
};

위의 구조체 Str1의 크기는 32바이트가 된다.

즉, 4바이트 x 5 = 20 바이트 + 패딩 12바이트가 들어가게 된다.

 

출처 - docs.microsoft.com/en-us/cpp/cpp/align-cpp?view=msvc-160

 


alignas(#)

 

 

 

alignas(#)는 표준에서 정한 예약어로써
객체 생성 시 메모리를 #바이트로 정렬하라는 의미를 컴파일러에게 전달한다.


 

// alignas_alignof.cpp
// compile with: cl /EHsc alignas_alignof.cpp
#include <iostream>

struct alignas(16) Bar
{
    int i;       // 4 bytes
    int n;      // 4 bytes
    alignas(4) char arr[3];
    short s;          // 2 bytes
};

int main()
{
    std::cout << alignof(Bar) << std::endl; // output: 16
}

 

출처 - docs.microsoft.com/en-us/cpp/cpp/alignment-cpp-declarations?view=msvc-160