Alignas in structures on 32-bit platforms

I get unexpected results when I run the following code for 32-bit x86 linux (compiler flags: g ++ -std = C ++ 14 -m32). I tried gcc and clang.

#include <iostream> using namespace std; struct S1 { uint64_t a; uint32_t b; }; struct S2 { alignas(uint64_t) char a[8]; uint32_t b; }; int main() { cout << "sizeof(S1)=" << sizeof(S1) << endl; cout << "sizeof(S2)=" << sizeof(S2) << endl; } 

Output:

 sizeof(S1)=12 sizeof(S2)=16 

What's going on here? Why are S1 and S2 different in size? As I understand it, 64-bit integer values ​​are 32-bit aligned on 32-bit x86 machines. This explains why the size of S1 is 12 bytes. But why does this not apply to S2?

+8
c ++ padding alignas
source share
1 answer

The alignof measures type alignment as a complete object; those. when it is allocated as a separate object or element of an array. This is not necessarily the same as alignment requirements of this type as a subobject; Are the members of the POD structure type or standard layout type consistent according to their alignment requirements?

The alignment of a 64-bit integer within the structure is specified using the x386 ABI of 4 bytes; gcc does not have the right to modify this, as this will violate binary compatibility with other object files and programs. However, it can align 64-bit integer objects with 8 bytes, as this does not affect the ABI and provides more efficient memory access.

+4
source share

All Articles