Boost logo

Boost :

Subject: [boost] [move] Implementing operator= in terms of pass-by-value and swap
From: Krzysztof Czainski (1czajnik_at_[hidden])
Date: 2012-07-24 08:12:37


Hello,

Implementing the assignment operator (that is, the copy-, move- and other
assignments) in terms of pass-by-value and swap is a common idiom [1].
{{{
T operator=( T b ) { swap(*this,b); return *this; }
}}}
If T is copy-constructible, the above works as a copy-assign. If T is
movable, the above works as a move-assign. And for anything convertible to
T the above assign will work (right?). Furthermore, this will also work for
movable but not copyable classes (right?).

It may not be the optimal version of assignment in some cases. In rare
cases it might even be incorrect - for types like std::vector, which aren't
expected to free reserved memory upon assignment. But assuming swap is a
cheap operation, it should be close to optimal in many if not most cases.
And in cases, where RVO kicks in, it may be even better than providing
separate overloads of operator= for lvalues and rvalues [2].

Boost.Move docs [3] suggest writing the separate overloads of operator=,
and in C++03 move emulation the macro BOOST_COPYABLE_AND_MOVABLE(classname)
provides a third overload (necessary for the emulation to work in C++03).

Should the user choose to write one overload of operator= in the
pass-by-value version, he needs to use a different macro, that doesn't
provide the additional overload of operator=. I found such a
macro: BOOST_COPYABLE_AND_MOVABLE_ALT(classname), but no docs about it.

I have the following suggestions, regarding Boost.Move:
1. Providing a macro, BOOST_MOVABLE(classname), that only provides the two
needed conversion operators. Or if that is the purpose
of BOOST_COPYABLE_AND_MOVABLE_ALT(classname), I couldn't find docs about
it. And to avoid a macro entirely, maybe it is possible to provide a CRTP
base class 'movable', that would provide these?
2. Now, that there's a separate macro, defining a movable class, it may
make sense to add a separate macro for making a class noncopyable. And we
already have a base class for that, if one wants to avoid a macro.
3. It would be nice if the docs [3] mentioned something about the
alternative of providing only one operator= passing by value.

[1] http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Copy-and-swap
[2] http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
[3]
http://www.boost.org/doc/libs/1_50_0/doc/html/move/implementing_movable_classes.html

Regards,
Kris


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