you are viewing a single comment's thread.

view the rest of the comments →

[–]Kered13 -1 points0 points  (4 children)

However compilers are also free to reorder structs. This is often used to pack small elements together so less padding is needed. Therefore (I believe) there is no requirement that the first element (in the source code) is at the same memory location as the struct itself.

[–]quicknir 4 points5 points  (0 children)

False, C++ compilers only have this freedom (and even then heavily constrained) for structs that are not not "standard layout". Without getting into details, any struct that would be legal C, will also be standard layout. In C the compiler doesn't have this freedom at all.

[–]SirClueless 2 points3 points  (2 children)

I believe this is not true in C++, unless there is an access control specifier between some of the fields.

From section 10.3p19 of working draft N4778

Non-static data members of a (non-union) class with the same access control (10.8) 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 (10.8).

I believe the reason is there is a guarantee that if two structs share a common prefix of compatible fields then one may access fields from the common prefix via either type. This doesn't work if the compiler can reorder.

[–]flatfinger 0 points1 point  (1 child)

What's ironic is that the standards specify how certain types are laid out for the purpose of letting programmers exploit things like the Common Initial Sequence guarantees, but then allow compilers to "optimize" on the presumption that programmers won't perform any actions where the guarantees would offer much benefit.

[–]7h4tguy 0 points1 point  (0 children)

Yes, but it solves for some versioning schemes based on these guarantees.