Boost logo

Boost :

From: David B. Held (dheld_at_[hidden])
Date: 2002-11-26 20:03:56


On c.l.c++.m, I argue that operator=() should not use the swap idiom
(largely based on comments I've seen Dave Abrahams make), but
that a named assignment function should instead provide assignment
with the strong guarantee. Since this is such a trivial function, I thought
it would be nice to encapsulate it in a simple class, provided below:

template <class T>
struct assignable
{
    T& assign(T t)
    {
        BOOST_STATIC_ASSERT(is_base_and_derived<assignable, T>::value);
        T* const me = static_cast<T*>(this);
        me->swap(t);
        return *me;
    }
};

I'm not sure about the type trait name. I just added that in for safety.
Of course, this class assumes that T has a non-throwing member
function named swap(). Obviously, it can be used like so:

class my_class : public assignable<my_class>
{
// ...
};

void foo(void)
{
    my_class a, b;
    // ...
    a.assign(b);
}

The nice thing about this approach, I think, is that if all the data members
have a basic guarantee assignment, then the default operator= works just
fine, and now you can add strong guarantee assignment with one line
(assuming you already had swap, of course).

If people like the idea, perhaps it could go into utility.hpp?

Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk