Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-08-28 11:35:21


On Tuesday 28 August 2001 11:50, you wrote:
> ----- Original Message -----
> From: Peter Dimov <pdimov_at_[hidden]>
> To: <boost_at_[hidden]>
> Sent: Tuesday, August 28, 2001 12:11 PM
> Subject: Re: [boost] Proposal: statefull objects
>
> > From: "Fernando Cacciola" <fcacciola_at_[hidden]>
> >
> > > (At least, let me know if the trick I used to remove the requirement of
> > > default-constructible is appropriate)
> >
> > Unfortunately not, it ignores T's alignment requirements AFAICS.
>
> This is what I was worry about, precisely. Thanks for looking at it.
>
> But I'am confused then...
> It is guaranteed that if the array of chars is allocated with new[] it has
> the appropriate aligment, but, from what you say, it appears that this is
> not the case when the array has automatic storage. Is that so?
>
> Hmm. Seems that you are right, pity! I've realized that allocator<> works
> because it always uses malloc(), so the guarantee is fulfilled. (of course!
> If optional<T> is created in the stack there's no way to align 'storage'
> properly!)
>
> Well, I think that optional<> is still usefull even if T is required to
> have a default constructor, but then it is not as nice as I thougth.
>
> (but I'll keep finding a way remove that requirement without allocating in
> the heap).

I was recently working on a variant type that was intended to be created on
the stack. I believe it is possible to do, though it isn't trivial :). What I
did was use the alignment_of metafunction in the type traits library to get
the alignment. Then I searched through a list of fundamental types to find
the fundamental type that has the same alignment (there is an assumption
here: that no structure has an alignment greater than that of a fundamental
type in the system). Once I found the fundamental type (call it
"alignment_type"), my storage layout was:

union {
  char data[sizeof(T)];
  alignment_type align;
};

This gives us a character array large enough to hold a T, and at the
alignment of T that is equivalent to the alignment of alignment_type.

I can upload the code to do this if anyone is interested. The rest of the
variant type is unfinished, but this part seems to work well enough :)

        Doug


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