Boost logo

Boost :

From: David Abrahams (david.abrahams_at_[hidden])
Date: 2002-03-04 08:59:18


----- Original Message -----
From: "brianjparker" <brianjparker_at_[hidden]>

> 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.

Agreed.

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

Unless, as you say, the user is really trying to save space and set
everything to align on 1-byte boundaries. Making things bigger in that
circumstance would be pretty ironic.

> 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).

I made almost this very suggestion on c++std-ext not long ago. However,
I don't see why the union should have to be anonymous or the item should
have to be the first member.

> 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

...minds think alike...

> , 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.

I don't like the restriction, but could live with it.

-Dave


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