From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2002-11-21 13:36:15


Hi All!

I've finally finished preparing this class for formal review.

{note: with just the basic exception safety guarantees, not with the
implementation I described recently in another post)

The headers, documentation and test files are packed in:

http://groups.yahoo.com/group/boost/files/optional.zip

I hereby ask this to be scheduled for formal review.
(I will also ask for a formal review of the Numeric Conversion Library
shortly...
but I wanted to have this one scheduled first since it is significantly
smaller)

Here is a description of the submission (adapted from the docs):

An object of type optional<T> can be used
to hold a value of type T which might have
an *uninitialized* state.
It has pointer semantics in order to deal
with its possibly uninitialized state;
but it does not require any allocation
or lifetime management.

The following cases shows the intended
usage for optional<>

//
// Usage Case A:
// Functions which may not have a value to return
// but cannot treat this situation as an error.
//
optional<char> get_async_input()
{
  if ( !queue.empty() )
       return optional<char>(queue.top());
  else return optional<char>(); // uninitialized
}

void recieve_async_message()
{
  optional<char> rcv ;
  while ( !!(rcv = get_async_input()) && !timeout() )
    output(*rcv);
}

//
// Usage Case B:
// Local variable which is never assigned a value.
//
optional<string> name ;
if ( database.open() )
{
  *name = database.lookup(employer_name);
}
else
{
  if ( can_ask_user )
    *name = user.ask(employer_name);
}

if ( !!name )
     print(*name);
else print("employer's name not found!");

//
// Usage Case C:
// Data member which can remain uninitialized.
//
class figure
{
  public:

    figure()
    {
      // data member clipping rect is
      // uninitialized at this point.
    }

    void clip_in_rect ( rect const& rect )
      {
         ....
         *m_clipping_rect = rect ; // initialized here.
      }

    // this can return NULL.
    rect const* get_clipping_rect()
      { return peek(m_clipping_rect); }

  private :

    optional<rect> m_clipping_rect ;
};

It uses aligned_storage<>, placement new and a explicit delete as the
implementation.

It only requires T's copy-constructor. The T's default constructor is not
required nor used.

It offers only the basic exception guarantees: the optionals are reset to
uninitialized if exceptions are thrown during updating operations.

TIA,

Fernando Cacciola