Reading through the reference of Copy assignment operator, i noticed that it suggests copy-and-swap idiom when it comes to the first option of the operator signature:
class-name & class-name :: operator= ( class-name )
And later on the same page the sample implementation is given as follows:
A& operator=(A other)
{
std::cout << "copy assignment of A\n";
std::swap(n, other.n);
std::swap(s1, other.s1);
return *this;
}
At this point I started to wonder why this implementation is swapping the values with the temporary instead of just moving them out of it? Moreover, I decided to inspect more carefully this excellent SO answer regarding copy-and-swap idiom and noticed that it not only suggests the same approach, but also swaps values with an rvalue reference in another snippet (which is also is not required to keep original values at the end of the scope):
dumb_array(dumb_array&& other) noexcept ††
: dumb_array() // initialize via default constructor, C++11 only
{
swap(*this, other);
}
This is not the first time I witness that swapping is used with the values which are supposed to be destructed at the end of the given scope, however I struggle to see any benefits over using std::move
with the "temporary" instead:
A& operator=(A other)
{
std::cout << "copy assignment of A\n";
n = std::move(other.n);
s1 = std::move(other.s1);
return *this;
}