0

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.

daohu527
  • 452
  • 4
  • 15

2 Answers2

3

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • But why 32 bit align will set `uint16_t b` to 4bytes – daohu527 May 07 '22 at 10:01
  • @dahohu527 It is stored at offset of 4 bytes from the beginning of the stucture because there is a sub object of 4 bytes at offset 0 so the offset 4 is the first unused byte so far. And that 4 byte offset satisfies the aligment requirement of `std::uint16_t` which is 2 bytes. – eerorika May 07 '22 at 10:03
  • it's puzzle me a lot, if alignas don't align the sub object, then what's the point of this syntax before struct. So what is the best way to align the subobject? – daohu527 May 07 '22 at 11:28
  • @dahohu527 Why would you want to align a "subobject" (field) from its natural alignment? – Ted Klein Bergman May 07 '22 at 11:29
  • I use `Eigen::Matrix4d` and the pcl library use `c[i] = _mm256_load_pd (tf.col (i).data ())` which tf is `Eigen::Matrix4d`, but `_mm256_load_pd ` need 256bits aligned, I'm not sure about why `Eigen::Matrix4d` is 256 aligned is ok , or the `tf.col (i).data ()` is??? – daohu527 May 07 '22 at 11:38
2

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
TonyK
  • 16,761
  • 4
  • 37
  • 72