Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2002-12-11 08:46:36

----- Original Message -----
From: "David Abrahams" <dave_at_[hidden]>
To: "Boost mailing list" <boost_at_[hidden]>
Sent: Tuesday, December 10, 2002 9:53 PM
Subject: Re: [boost] Formal review: Optional library

> [SNIP]
> "Joel de Guzman" <djowel_at_[hidden]> writes:
> >> Not so...
> >> The low-level implementation is like a variant ONLY is the wrapped
object is
> >> not a POD.
> >> When you have, say, optional<int>, the implementation uses: struct {
> >> m_value ; bool m_initialized }
> >> As a result, value access, via operator*() is more efficient since it
> >> doesn't dereference a pointer.
> >
> > That depends on how the variant is implemented. Which variant
> > implementation are you referring to? I'm sorry. I'm confused with
> > what you are saying. I can't see why it is more efficient. Neither do
> > I see a dereference in any case.
> I'm with Joel on this one. It seems to me that no special optimization
> should be needed for PODs; all you should need is some aligned storage
> in which to construct the contained object and one or more bits to
> indicate which of the allowed types (if any) is held there.
Let's see:

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 ;
} ;

The object is effectively contained in an aligned storage.
AFAIK, to access the object I need to address the storage, for which
I need a pointer. But then, in order to return a reference to
the object, I need to dereference the pointer.

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.

Fernando Cacciola

Boost list run by bdawes at, gregod at, cpdaniel at, john at