Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-10-10 17:46:18


"Andrei Alexandrescu" <andrewalex_at_[hidden]> writes:

Oh, and by the way...

> * Here are current state-of-the-art recommended canonic signatures and
> implementations of some primitive functions:
>
> class T
> {
> ...
> T& operator=(const T& rhs)
> {
> T copy(rhs);
> rhs.swap(*this);
> return *this;
> }
> };
>
> const T operator+(const T& lhs, const T& rhs)
> {
> T copy(lhs);
> return copy += rhs;
> }
>
> I reached the conclusion that the signatures and implementations above are
> about the worst possible to recommend, with or without ZUTO in action. I
> consider them simply wrong.

If you've been talking with Scott Meyers recently you might already
know that I certainly agree about operator= for lots of reasons. The
only excuse for the implementation above is that it's easy to do
correctly (which is sometimes reason enough). Some people like to
recommend that technique as the default in order to get strong the
strong guarantee for operator=, but that is almost always flawed for
two serious reasons:

  1. Copy-and-swap is an incredibly drastic step to take,
     efficiency-wise.

  2. The SGI argument against putting multithread locks on every
     operation applies here as well: you pay for "safety" at what is
     almost certainly the wrong level of granularity. Systems are
     composed of multiple parts and operations, and often you need
     locks around a whole sequence of steps. Similarly, if the client
     really needs the strong guarantee, it's likely to be for more
     operations than just the assignment. If you make strong
     assignment by using copy/swap, but the client needs an assignment
     followed by a push_back to give the strong guarantee, they have
     to copy the object anyway and your copy is completely
     wasted. Building up large systems around operations which all
     copy/swap to get atomic behavior would be an efficiency disaster.

-- 
           David Abrahams * Boost Consulting
dave_at_[hidden] * http://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