Jorgen Grahn <
grahn...@snipabacken.se> writes:
> On Tue, 2020-09-29, Keith Thompson wrote:
>> Richard Damon <Ric...@Damon-Family.org> writes:
>>> On 9/28/20 2:31 PM, olcott wrote:
>>>
>>>> All that I had to do to optimize the need for padding of the
>>>> reference struct is simply sort the members in size order from
>>>> largest to smallest. Certainly every compiler could compare the
>>>> need for padding of the specified version with the sorted version
>>>> and then know whether or not sorting reduces padding
>>>> requirements.
>>>
>>> I believe the standard requires that the order of the members in
>>> the struct has to match the order they are declared in the struct,
>>> at least as long as a access specifier doesn't exist between them.
>>>
>>> That rule comes from C, without the exception since C doesn't
>>> have access specifiers. As you alluded to elsewhere, allowing
>>> rearangement can cause all sorts of issues with code that makes
>>> some otherwise fairly safe assumptions. I suspect that the rule
>>> came out because the early compilers [weren't] smart enough to
>>> rearrange, then a lot of code was built with that assumption,
>>> and it became effectively impossible to safely rearrange so it
>>> was defined that it couldn't.
I believe it was more deliberate than that. See below.
> If that's what happened, it's a really bad combination: letting
> bad code prevent important optimizations. I can see no reason for
> portable code to know the struct layout (except perhaps that you
> can cast between &foo and &foo.first_element).
>
> One could easily imagine each ABI defining struct layout, with
> rearrangements, in such a way that waste is minimized.
I think you're overlooking an important property, and one that
pertains to having code be portable. The rule in C (and later
also in C++) is not just that struct members are positioned in
the same order as they are declared, but also that their offsets
depend only on (the types of) the previously declared members.
This rule must be followed in order to (reasonably) support the
semantics related to /common initial sequences/, a term defined
in both the C and C++ standards. The notion that struct layouts
could be rearranged as suggested above is therefore not feasible.