Optimal struct layout template?

Rainer Deyke rainerd at eldwood.com
Thu Dec 18 19:47:43 PST 2008


Sergey Gromov wrote:
> I think this is not something you can assume or not assume.  The set of
> conditions you mention is required and sufficient to respect alignment
> requirements of array elements while obeying the rules of pointer math.
> You cannot change them until you drop either pointer math or alignment
> guarantees.

You could split the sizeof property into two separate:
   real.alignof = 16
   real.unpaddedsizeof = 12
   real.paddedsizeof = 16

   T.paddedsizeof = (T.unpaddedsizeof + T.alignof - 1) & ~T.alignof;

Arrays would always use paddedsizeof to calculate addresses.  Structs 
could use unpaddedsizeof and squeeze one or more additional variables 
into the padding space.  The same applies to structs:

   struct C { int a; byte b; }
   C.alignof = 4
   C.unpaddedsizeof = 5
   C.paddedsizeof = 8

There is one problem with this technique.  Because the padding space of 
a variable may contain another variable, when the variable is copied, 
only unpaddedsizeof bytes may be copied or the other variable will be 
clobbered.  I expect that this partially negates the advantage of 
properly aligning the variable.


-- 
Rainer Deyke



More information about the Digitalmars-d mailing list