Home > Enterprise >  align array elements differently in aligned union
align array elements differently in aligned union

Time:01-25

I'm using SSE/AVX and I need to store aligned data. how ever, my data can be of different types. so I use a union like this

union Data
{
    bool Bools[128];
    int32 Ints32[128];
    int64 Ints64[128];
    // ... other data types
} data;

Can I do the following?

union alignas(16) Data
{
    alignas(4) bool Bools[128];
    alignas(4) int32 Ints32[128];
    alignas(8) int64 Ints64[128];
    alignas(16) Bar Bars[128]; // Bar is 16 bytes
} data;

so I expect Ints32 and Bool elements to be aligned as 4 bytes, yet Int64 elements are aligned as 8 bytes.

because of Bar first element of each array (or basically &data) should also be aligned to 16 bytes. but elements of each array should be aligned as stated. so is my union correct?

CodePudding user response:

The alignment specifier applies only to the entity it defines. It applies to the whole class (union) object's alignment or the alignment of the individual arrays. It never applies to elements of the array.

The alignment of elements in an array of type T can never be guaranteed to be stricter than the size of T, because elements of an array must be allocated contiguously in memory without padding. This is for example necessary so that pointer arithmetic can work. The type of the member doesn't include any information about the alignment specifier you used, so e.g. evaluating Bools[i] must be sure how far apart individual elements of type bool and can't adjust to alignment specifiers.

If you want to adjust element-wise alignment then you need to specify your own type with the required alignment and form an array of that type.

Because the initial address of the subobjects of a union has to be equal to that of the union object itself, there is also no point to add weaker alignment specifiers to the subobjects. They can't have any effect.

  • Related