Skip to content
Search

C++:alignas

lastmod 2018-08-17created 2016-11-188 edits

alignas

The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user-defined types.

alignof

Similarly, the alignof operator is a portable, standard way to obtain the alignment of a specified type or variable.

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 ↩