Boost logo

Boost :

From: JOAQUIN LOPEZ MU?Z (joaquin_at_[hidden])
Date: 2007-06-03 11:40:01


----- Mensaje original -----
De: "Aaron W. LaFramboise" <aaronrabiddog51_at_[hidden]>
Fecha: Domingo, Junio 3, 2007 5:12 pm
Asunto: [boost] Uninitialized storage container to delay construction?
Para: boost_at_[hidden]

> Does Boost have some sort of uninitialized storage container?
> Presently, I use this pattern if I want to delay construction of a
> sub-object.
>
> class my_class {
> public:
> my_class() {
> // ...
> subobject = auto_ptr<type>(new type(params));
> }
> private:
> auto_ptr<type> subobject;
> };
>
> But I'd like something similar that didn't use the heap, but
> instead
> allocated the storage for the sub-object within the class object
> itself.
> Perhaps it would look like this.
>
> class my_class2 {
> public:
> my_class2() {
> // ...
> subobject.construct(params);
> }
> private:
> uninitialized_container<type> subobject;
> };
>
> A TR1 array<T, sizeof(T)> almost works, except for these points:
> (1) It doesn't provide proper alignment guarantees.
> (2) It doesn't call the destructor when it is destroyed.
>
> So, does Boost have any such thing?

I think you want to use aligned_storage and alignment_of
from Boost.TypeTraits:

  aligned_storage<
    sizeof(type),alignment_of<type>::value>::type subobject;

which provides the alignment guarantees. (2) OTOH is not taken
care of by this construct, so it' still your responsibility
to clean up subobject (by doing something like
((type*)&subobject)->~type()) when appropriate.

HTH,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo


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