On 08/21/10 06:30, Francesco S. Carta wrote:

[snip]

> I've created a struct that occupies 64 bytes of storage, then I

> dynamically allocated it and I checked its address to see if, as I was

> expecting, it was a multiple of 64. As it turned out, it wasn't, showing

> me that my assumption was stupid at best.

>

> I have no idea about where I have taken that misconception from, I could

> very well have made it up all by myself.
[snip]

Hi Francesco.

I struggled a few yrs (months?) ago about that and think I've

figured it out.

The alignment of your 64 byte long structure is dependent on the

types contained in the structure.

Using variadic template:

http://www.osl.iu.edu/~dgregor/cpp/v...templates.html
notation, augmented with:

template

< unsigned Index

, typename... T

>
struct at_c

{

typedef

//T...[I] the I-th type in T...

type

;

};

assume:

template

< typename... T

>
struct C

{

typename at_c<1,T...>::type m_1;

typename at_c<2,T...>::type m_2;

...

typename at_c<n,T...>::type m_n;

};

then, again

then alignof(C) is *only* a function of the alignments of

T... .

I'm pretty sure:

eq[1]: alignof(C) == fold(lcm,1,alignof(T)...)

where fold is the haskell foldl or foldr

which is basically the stl::accumulate.

alignof(T)... basically expands to:

alignof(T_1), alignof(T_2), ..., alignof(T_n)

NOTE, sizeof doesn't appear in eq[1]:.

If eq[1] is true, then the

offsets for all the members can

be easily calculated by assuring that

the offset of m_i in C is divisible by the

alignof(T_i). This is because, since the start of C is

at an address that is divisible by alignof(T_i)

(since alignof(C) is a multiple of alignof(T_i),

since alignof(C) was calculated as the lcm of all of

the alignof(T...)) , then m_i will be located at an address divisible by

aligndof(T_i).

All this is implemented with templates here:

http://svn.boost.org/svn/boost/sandb...osite_storage/
Now the one thing missing from this explanation is the role

of size. Now in order for all C's in:

C cvec[2];

to be properly aligned, the sizeof(C) must also be a multiple

of the alignof(C). Thus there may be some padding at the

end of C to achieve this. Likewise, in order to calculates

the offset of m_i to put m_i at the proper alignment, some

padding may also be needed. I'm pretty sure:

Sorry if this seems complicated. It is, at least to me

HTH.

-Larry