Optimal struct layout template?

Denis Koroskin 2korden at gmail.com
Thu Dec 18 05:12:22 PST 2008


On Thu, 18 Dec 2008 01:38:32 +0300, Sergey Gromov <snake.scaly at gmail.com>  
wrote:

> Thu, 18 Dec 2008 00:21:58 +0300, Denis Koroskin wrote:
>
>> On Thu, 18 Dec 2008 00:12:18 +0300, Sergey Gromov  
>> <snake.scaly at gmail.com>
>> wrote:
>>
>>> Tue, 16 Dec 2008 10:09:41 +0100, Don wrote:
>>>
>>>> Example 2:
>>>> struct Foo { double, int } // 12 byte size, wants 8-byte alignment.
>>>
>>> Foo.sizeof is 16.
>>>
>>
>> It is 12 with align(1) (I see no problem with it).
>
> With align(1) the Foo.alignof is 1 so there is no problem to talk about.
> The problem is when you have elements with non-trivial alignment
> requirements and want to pack them as tightly as possible.
>

No, there is. You should have structure as follows:

align(1):
struct Foo
{
     char c;
     double d;
     short s;
     bool b;
}

it should be reordered to (one of the solutions):

align(1):
struct Foo
{
     char c;
     bool b;
     short s;
     double d;
}

so that Foo.d.alignof == 8. Align(1) is still necessary so that Foo.sizeof  
== 12.

>>> The thing is, array of Foo's must be properly aligned, and &foo[1] must
>>> be cast(byte*) &foo[0] + Foo.sizeof.  This means that Foo.sizeof must  
>>> be
>>> itself 8-aligned.  The solution is { Foo, Foo, int, int }.
>>
>> Stop right there. You can't access &foo[1] no matter what align or
>> structure layout is used. Example:
>>
>> align(default):
>> struct Data
>> {
>>      int i1;
>>      short s2;
>>      char c1;
>>      int 12;
>> }
>>
>> What is &i1[1]?
>
> i1 is not an array.
>
> Sorry I wasn't clear enough.  I was talking about an imaginary array of
> Foo's:
>
>   Foo[] foo;
>
> You must admit that foo[1] and &foo[1] makes perfect sense for such
> construct.  And that
>
>   cast(byte*) &foo[1] - cast(byte*) &foo[0] == Foo.sizeof
>
> must hold.

This will *always* be true no matter what align/data layout is used.



More information about the Digitalmars-d mailing list