Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2002-12-11 09:58:43


----- Original Message -----
From: "David Abrahams" <dave_at_[hidden]>
To: "Boost mailing list" <boost_at_[hidden]>
Sent: Wednesday, December 11, 2002 11:14 AM
Subject: Re: [boost] Formal review: Optional library

> "Fernando Cacciola" <fernando_cacciola_at_[hidden]> writes:
>
> > Currently, the non-POD case implementation goes like this:
> >
> > (this is a sketch actually)
> >
> > template<class T>
> > class optional1
> > {
> > optional1 ( T const& v ) { p = new (buffer.address()) T(v) ; }
> >
> > T const& operator *() { return *p; } // Dereference here
> >
> > aligned_storage<T> buffer ;
> > T* p ;
> > } ;
>
> There's no need to store p. You can just use
> static_cast<T*>(buffer.address())
>
Yes.. I just shown the pointer explicitely.
The result of the static_cast<> is a pointer, so to obtain a reference (for
the operator*) you need to 'actually' dereference this poiner.

> > OTOH, when T is a POD, so there is no need to bypass its ctor
> > (since it has a trivial ctor),
> > the implementation goes like this:
> >
> > template<class T>
> > class optional2
> > {
> > optional2 ( T const& val ) v(val) {}
> >
> > T const& operator *() { return val; } // No Dereference here
> >
> > T val ;
> > } ;
> >
> > Anyway, if yoy know how to make an efficient implementation like
> > the second one with an aligned storage I'll be happy to use it.
>
> Why do you think that will be any more efficient than the other
> implementation when T is POD?
>
For POD types: operator*() "directly" returns the value.
The key is that for POD types, since optional wraps just T (unlike any
variant) and nothing else, aligned_storage is not required.
optional<> simply contains a data member of type T, that's all.

If you still don't see it I can show you the typical machine generated code
for both implementations for operator*().

Fernando Cacciola


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