Skip to content

C++:alignas

alignas

alignas 형식 지정자는 변수 및 사용자 정의 형식의 사용자 지정 맞춤을 지정하는 포팅 가능한 C++ 표준 방법입니다.

alignof

마찬가지로 alignof 연산자도 지정된 형식 또는 변수의 맞춤을 얻는 포팅 가능한 표준 방법입니다.

align_malloc

int *pbuf = (int *)_aligned_malloc(sizeof(int) * 1024, 4096);
// ...
unsigned int verifyZeroCopyPtr(void *ptr, unsigned int sizeOfContentsOfPtr)
{
    int status; //so we only have one exit point from function
    if((uintptr_t)ptr % 4096 == 0) { // page alignment and cache alignment
        if(sizeOfContentsOfPtr % 64 == 0) { // multiple of cache size
            status = 1;  
        } else {
            status = 0;
        }
    } else {
        status = 0;
    }
    return status;
}

Example

struct alignas(16) Bar
{    
    int i;       // 4 bytes
    int n;      // 4 bytes
    alignas(4) char arr[3];
    short s;          // 2 bytes
};
// ...
cout << alignof(Bar) << endl; // output: 16

Troubleshooting

MacOS X memory alignment

I had a hard time finding a definitive statement on MacOS X memory alignment so I did my own tests. On 10.4/intel, both stack and heap memory is 16 byte aligned. So people porting software can stop looking for memalign() and posix_memalign(). It’s not needed.

See also

Favorite site

References


  1. How_to_Increase_Performance_by_Minimizing_Buffer_Copies_on_Intel_Processor_Graphics.pdf 

  2. Data_alignment_and_SIMD_architecture_operations_-_DBguide.pdf