Boost logo

Boost :

From: brianjparker (brianjparker_at_[hidden])
Date: 2002-03-04 03:59:22


--- In boost_at_y..., "David Abrahams" <david.abrahams_at_r...> wrote:
> Thinking a little further, I think what we want is this:
>
> take the union of all types whose alignment is <= that of the target
> if the alignment is not a multiple of the target alignment,
> take the union of all types whose size is <= that of the target
> if the alignment is not a multiple of the target alignment,
> take the union of all the types and cross fingers
> assert success.
>
> The intent of this approach is to find a minimally-aligned type
which
> ensures alignment of the target while maintaining compatibility
with brian's
> basic strategy.
>
> It seems like anything more simple-minded will either over- or
under-align
> in more cases. Over-alignment is wasteful, and under-alignment is
dangerous.

Hi,

I suppose there is a tradeof here between having an over-aligned
result type vs an excessively large result type.

For example, on an architecture (or compiler packing option) in which
all types have an alignment of 1, the above algorithm will cause the
union to include all types and so will give an excessively large
result.

I think that, in theory, a more efficient algorithm would be-

take the union of all types whose alignment is <= that of the target
AND whose alignment <= target alignment,
     if the alignment is not a multiple of the target alignment,
         take the union of all the types and cross fingers
 assert success.

,but in practice under Windows and Linux the first algorithm probably
gives as optimal results as are possible.

I think that in the longer term, the best fully portable solution to
this problem would be a language change that simply allowed non-POD
members in *anonymous* unions (expect perhaps as the first member) to
ensure the correct alignment of the union directly and optimally
using the usual C idiom. (Note that the semantics of anonymous unions
would be otherwise completely unchanged i.e. non-POD members would
not be automatically constructed or destroyed).

e.g.

template<class A, class B, class C>
class valunion {

 int discriminant;
  // ... code here to correctly construct and destroy into buffer
 
 private:

 union {
   char buffer[MAX_SIZE_OF_A_B_C];
   A dummy1; // OK, non-PODs allowed here
   B dummy2;
   C dummy3;
  }

};

When I suggested this previously, it was pointed out that this could
allow potentially dangerous usage if allowed in general unions. This
is why this proposal is limited to anonymous unions only, which,
being restricted to a containing class, can be used to align class
data members and at the same time prevent unsafe usage of the non-POD
anonymous union members.

(BTW, the approach I used in force_align<> was originally based on a
code sample by Valentin Bonnard)

Cheers,
Brian Parker


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk