|
Boost : |
From: Fernando Cacciola (fcacciola_at_[hidden])
Date: 2001-09-13 18:18:34
The following is derived from conversations with Gennadiy Rozental about the
optional<> class.
My initial design used a mechanism that allows optional<T> to bypass T::T().
This capability is required in order to allow a type without a default
constructor to be used with optional<T> ; and it also offers room for
optimization since the default constructor may not be trivial.
Gennadiy was concerned about the unnecessary overhead introduced by the
bypass mechanism in cases where T is a POD; and he made a good job at
drawing my attention to this issue.
There are two possible implementations:
a value-based implementation, where optional<T> contains:
T v ; bool initialized ;
and a pointer-based implementation, where optional<T> contains:
T* v ; aligned_storage<T> buffer;
I setup a test bed and verified that for POD types, the overhead is about as
twice as much executed code for the typical operations.
Therefore, I decided to do the following:
I believe that the implementation choice for optional<T> depends *only* on
T -not in the context in which optional<T> is used-; therefore, the optional
class can automatically select the appropriate implementation based only on
the type T. No policy class is required, or at least, not as a second
template argument.
I change the code to reflect this.
The new optional<T> uses ::boost::is_POD<T> to select a value or
pointer-based implementation.
The interface allows the user to override the default impl selection for any
type T to accommodate his/her needs.
I also made up my mind about how to let the user test if a given optional is
initialized or not.
Previously, optional<> used operator void*() to allow expressions of the
form:
if ( opt ) or if ( opt != NULL )
After *a lot* of consideration, I decided to support only the 'bang-bang'
idiom:
if ( !!opt ) means initialized.
if ( !opt) means uninitialized.
I just hope enough people is aware and fond of this very useful technique,
because it removes all the problems with the other approaches.
The new optional.hpp header contains a small rational for this design
decision.
I also refactored things and updated the documentation and the test bed.
The new stuff has been updated in the FilesSection under optional class (as
before).
I also included a zip file for easier downloading.
Opinions are welcome.
Thanks,
Fernando Cacciola
Sierra s.r.l.
fcacciola_at_[hidden]
www.gosierra.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk