Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11?

First of all, it is generally unnecessary to write a swap function in C++11 as long as your class is movable. The default swap will resort to moves:

void swap(T& left, T& right) {
    T tmp(std::move(left));
    left = std::move(right);
    right = std::move(tmp);
}

And that’s it, the elements are swapped.

Second, based on this, the Copy-And-Swap actually still holds:

T& T::operator=(T const& left) {
    using std::swap;
    T tmp(left);
    swap(*this, tmp);
    return *this;
}

// Let's not forget the move-assignment operator to power down the swap.
T& T::operator=(T&&) = default;

Will either copy and swap (which is a move) or move and swap (which is a move), and should always achieve close to the optimum performance. There might be a couple redundant assignments, but hopefully your compiler will take care of it.

EDIT: this only implements the copy-assignment operator; a separate move-assignment operator is also required, though it can be defaulted, otherwise a stack overflow will occur (move-assignment and swap calling each other indefinitely).

Leave a Comment