Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-11-29 17:13:26


"David B. Held" <dheld_at_[hidden]> writes:

> 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.

When neccessary. It's not as though a "strong guarantee assignment" is
a fundamental operation which people often need.

> 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.

Which type trait name?

> I just added that in for safety.

Added what?

> 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>
> {
> // ...
> };

Don't you want the static assertion in the constructor or in the class
body itself? Do you want to have to instantiate assign() to find out
you've misused this template?

> 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?

I'm not sure it's useful enough to warrant putting it in
utility.hpp. Also I have concerns about the name "assign()", since
that is used in the standard library to mean something slightly
different.

-- 
                       David Abrahams
   dave_at_[hidden] * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution

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