Aside from that the ints in the following example might not be layouted as if they werre following in a normal array: is this an illegal aliasing in C++ ?
struct S
{
int a, b;
};
void fn( S &s )
{
(&s.b)[-1] = 123;
}
Aside from that the ints in the following example might not be layouted as if they werre following in a normal array: is this an illegal aliasing in C++ ?
struct S
{
int a, b;
};
void fn( S &s )
{
(&s.b)[-1] = 123;
}
It is illegal (undefined behavior, see @user17732522's comment and this question pointed out by @Özgür Murat Sağdıçoğlu for why exactly).
Even for POD (plain old data) types, compilers are allowed to include padding between members. In the case of
struct S
{
int a, b;
};
there is very likely no padding, as both members have the same alignment requirements (I could however find no reference, if that is required by the standard).
In another case like
struct S
{
char a;
int b;
};
there will be an implementation defined amount of padding between the members and pointer magic, like you did in your question will be non-portable at least.
Generally speaking the standard gives you the following guarantees about the memory layout of POD types [1]:
offsetof
macro [2] to get the offsets of the different members.Thus when working with pointers to data members, try to use those facilities and avoid relying on false assumptions about the data layout.