Say, I have an aligned array
alignas(X) char arr[sizeof(X)];
Is the pointer
X * ptr = reinterpret_cast<X*>(arr);
guaranteed to be properly aligned according to the alignment requirements of X?
It seems obvious that this is the case, however it does not appear to be obvious from the C++ standard.
I don't find anything in the standard that would prevent a compiler to align a struct of the form
struct X
{
int16_t a;
int32_t b;
int16_t c;
};
like this in memory:
+-+-+-+-+-+-+-+-+
|a|a|b|b|b|b|c|c|
+-+-+-+-+-+-+-+-+
^
aligned to 32-boundary
so that the objects of type X are aligned in such a way that no padding is needed and b is aligned correctly at the same time to a 32-bit boundary. The statement (N4713, § 6.6.5.1)
An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.
is not violated by that and I don't see any other statement in the standard that violates it.
Xcontains no padding but whereint32_tis required to have 32 bit alignment? And are you asking which part of the standard prevents this case? - François AndrieuxX x; auto y = &x.b;needs to produce a usable pointer tob, likely as part of the definition of how the address of operator is defined by the language. - François Andrieuxbbe aligned to a 32 bit boundary, if the start of the structure is already aligned to a 32 bit boundary (e.g. coming frommallocornew).bbeing aligned to 32 bits (on an 8 bit byte addressable system) requires the start of the structure being aligned to an address that leaves a reminder of 2 when divided by 4. - Kaz