
On Mon, 14 Feb 2005 20:35:31 -0500 "Joe Gottman" <jgottman@carolina.rr.com> wrote:
I just discovered that optional<T> is not safe under self-assignment. Consider the following code fragment:
boost::optional<long> x(1); //At this point x is initialized and *x == 1 x = x; //x should be unchanged, but instead x is now uninitialized
Optional's assignment operator looks like
optional& operator= ( optional const& rhs ) { this->assign( rhs ) ; return *this ; }
and assign is defined by
void assign ( argument_type val ) { destroy(); construct(val); }
Thus, if (this == &rhs) in operator=(), any value held by rhs will be destroyed.
Actually, there are multiple assignment operators, with different levels of complexity and "bugginess." It seems to me that implementing the canonical assignment operator would work fine... optional & operator=(optional const & rhs) { optional tmp(rhs); optional_swap(*this, tmp); return *this; } I know it is has a little more overhead, but I am pretty sure there are enough copy-ctors to match the assignement signatures that each assignemnt operator could be implemented in this manner fairly simply. This actually brings me to a more broad question... with a fairly well accepted practice for safe implementation of assignment operators, some boost libs seem to go out of their way to implement something different. Is this because of perceived performance issues, or something else?