From: David Abrahams (dave_at_[hidden])
Date: 2003-10-29 19:05:14
Brian McNamara <lorgon_at_[hidden]> writes:
> On Wed, Oct 29, 2003 at 01:27:08AM -0800, Jaap Suter wrote:
>> Well, it allows me to do exactly the thing posted in the original message;
>> implement a state machine where state entries and exits are implemented
>> through ctors and dtors. I can probably think of a few other cases where
>> such a defined order can be exploited too.
>> Personally, I think it makes sense conceptually too. If I use the assignment
>> operator on any other class, then in a sense the existing state is destroyed
>> first, and then the new state is copied in. I'm not saying that it's
>> implemented like that (as no sane person would do), but the similarities are
>> there. I think it makes sense to let variant behave the same.
> I kind of agree with the conceptual similarity, but I don't agree
> that a class "should" actually exhibit behavior like this. Again,
> it's all owing to details of C++ and the "strong guarantee", but
> I've come to think of assignment as
> T tmp( data );
> this->swap( tmp ); // nothrow
> // tmp.~T()
> which destroys old data only after new data has been safely
> constructed. Indeed, many classes might make arbitrary copies of
> data along the way, too.
This is a misconception. In many cases (see vector assignment)
producing the strong guarantee induces unavoidable overhead for a
"benefit" that the client may not need at all (e.g. the vector was on
the stack and will be destroyed anyway). Since the strong guarantee
is generally easy to add at an outer layer when needed as long as
there's a nothrow swap, the "don't pay for what you don't use"
principle dictates that copy/swap should never be used inside an
assignment operator to get it.
-- Dave Abrahams Boost Consulting www.boost-consulting.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk