For this reason, a lot of compilers have options to not strictly enforce the aliasing rules
[edit] Also C and C++ are both permitted to reorder structs, it's just that they don't because that's the easiest way to follow the standard.
For this reason, a lot of compilers have options to not strictly enforce the aliasing rules
[edit] Also C and C++ are both permitted to reorder structs, it's just that they don't because that's the easiest way to follow the standard.
A structure type describes a sequentially allocated
nonempty set of member objects (and, in certain
circumstances, an incomplete array), each of which
has an optionally specified name and possibly
distinct type.
and §6.5.8 says: If the objects pointed to are members of the same
aggregate object, pointers to structure members
declared later compare greater than pointers to
members declared earlier in the structure,…§9.2.12 says:
Nonstatic data members of a (non-union) class declared without an
intervening access-specifier are allocated so that later members
have higher addresses within a class object. The order of allocation
of nonstatic data members separated by an access-specifier is unspecified (11.1)
This means, that under a strict reading, even the following struct can have its members reordered: struct foo {
int a;
public:
int b;
}> Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11).
Just type casting a struct to a char-pointer and dumping it straight out on the network or to persistent storage is code you see every day.
> Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order which they are declared.
Is that the same standard that says it is illegal to write to one entry and read from another in a union* ?
* Note : special situation of identical fields in a structure
If the member used to access the contents of a union object
is not the same as the member last used to store a value in
the object, the appropriate part of the object representation
of the value is reinterpreted as an object representation in
the new type as described in 6.2.6 (a process sometimes called
"type punning"). This might be a trap representation.Is that feasible? Doing so would require that the order of the member addresses not correspond to their layout in memory.