|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-02-15 14:33:59
David Abrahams wrote:
> Jody Hagins <jody-boost-011304_at_[hidden]> writes:
>
>> 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 wish people would stop calling it that. It's easy, but it's
> overkill.
No, it is not overkill. It is the easiest way to implement a correct
assignment operator. Forget performance. Subtle bugs in assignment are
notoriously hard to find. To give the "canonical" example:
optional& operator=( T const & t )
{
// destroy and recreate
}
Consider what happens when an optional holds a tree node and is assigned a
child of that node. Or in general, when the 'destroy' step indirectly
destroys the right hand side.
A correct assignment operator should typically handle self-assignment
without an explicit test. Adding the test usually doesn't fix the problem,
only its most obvious manifestation.
Of course if correctness is not a concern, copy+swap is always overkill.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk