Home > Software engineering >  why alignas(64) not aligned with 64
why alignas(64) not aligned with 64

Time:05-08

why alignas(64) not aligned with 64? for example:

struct alignas(32) st32
{
    float a;
    uint16_t b;
    uint64_t c;
};

struct alignas(64) st64
{
    float a;
    uint16_t b;
    uint64_t c;
};

int main()
{
    st32 x;
    st64 y;

    std::cout
        << "alignof(st32) = " << alignof(st32) << '\n'
        << "alignof(st64) = " << alignof(st64) << '\n'
        << "&st32 a: " << &x.a << '\n'
        << "&st32 b: " << &x.b << '\n'
        << "&st32 c: " << &x.c << '\n'
        << "&st64 a: " << &y.a << '\n'
        << "&st64 b: " << &y.b << '\n'
        << "&st64 c: " << &y.c << '\n'; 
}

The results is

alignof(st32) = 32
alignof(st64) = 64
&st32 a: 0x7ffc59fc9660
&st32 b: 0x7ffc59fc9664
&st32 c: 0x7ffc59fc9668
&st64 a: 0x7ffc59fc9680
&st64 b: 0x7ffc59fc9684
&st64 c: 0x7ffc59fc9688

why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688, beacause the address need to 64bits aligned, we should leave 0x7ffc59fc9684-0x7ffc59fc9688 blank, and start next data at 0x7ffc59fc9688.

CodePudding user response:

why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688

Aligning a structure does not affect the alignment of the sub objects of the structure. The address of the enclosing structure is 64 byte aligned, and b is the second member after a 4 byte sized a, so it's reasonable to expect b to not be 64 byte aligned.

if alignas don't align the sub object, then what's the point of this syntax before struct.

The point is to align the class itself. This is sometimes needed for example for SIMD instructions.

CodePudding user response:

This will give you what you seem to want:

struct alignas(64) st64
{
    float a;
    alignas(64) uint16_t b;
    uint64_t c;
};

Output:

alignof(st32) = 32
alignof(st64) = 64
&st32 a: 0x7ffe33498ae0
&st32 b: 0x7ffe33498ae4
&st32 c: 0x7ffe33498ae8
&st64 a: 0x7ffe33498b00
&st64 b: 0x7ffe33498b40
&st64 c: 0x7ffe33498b48
  • Related