The copy & swap idiom allows you to implement assignment operators and even the move constructor using a swap operation.
?inline
T& T::operator=(
T other)
{
using std::swap;
swap(*this, other);
return *this;
}
?inline
T& T::operator=(
T&& other)
{
using std::swap;
swap(*this, other);
return *this;
}
Because of argument-dependent lookup (ADL),
our own swap(T&, T&)
function may be called instead of
std::swap.
✅ simple implementation of assignments (and move constructor)
✅ well-defined self-assignment
✅ noexept copy/move assignment
if std::is_nothrow_swappable
❌ copying always takes place, even for self-assignment
<:stackoverflow:874353689031233606> What is the copy-and-swap idiom? (must read!)