简体   繁体   中英

Align C++ array of structs on 64-bit boundaries?

I have an array of 64-bit structs that I'd like to align on 64-bit boundaries:

struct AStruct
{
    int x;
    int y;
};

std::array<AStruct, 1000> array;   // I'd like to align this on 64-bit boundary

I know the attribute is __attribute__((__aligned__(64)) but I'm unsure whether I need to align each individual struct, the entire array or specify the attribute for both?

Compiler is Clang

I know the attribute is __attribute__((__aligned__(64))

That is a language extension. There is no need to use it since there is a standard keyword to specify alignment: alignas . Example to align the array to 64 bits:

alignas(64 / CHAR_BIT) std::array<AStruct, 1000> array;

I'm unsure whether I need to align each individual struct, the entire array or specify the attribute for both?

There is no need for both.

Either works as far as aligning the array is concerned. If you want all instances of the class including others outside of this array to be aligned, then specify it for the class. If you want only this array to be aligned, then specify it for the variable.


I have an array of 64-bit structs

Note that while your class may be 64 bits on some systems, it is not 64 bits on all systems. It can range from 32 bits (16 bit int ) to 128 bits (64 bit int ).

You need to align the array only:

alignas(8) std::array<AStruct, 1000> array; //aligned on 64-bit boundary

See: alignas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM