The copy-and-swap idiom is a safe implementation of the copy and move assignment (operator=). It is safe because:

  • If the copy throws, *this is unmodified giving strong exception guarantee.
  • Self-assignment works without this != &other check.
  • The old data is freed by other's destructor, so there is no risk of double free.

operator= argument other is passed by value (which is a copy):

Buffer& operator=(Buffer other) {
  std::swap#include <utility>(size, other.size);
  std::swap#include <utility>(data, other.data);
  return *this;
}

The other argument is copy-constructed or move-constructed depending on lvalue or rvalue:

Buffer b1(10);
Buffer b2(20);
b2 = b1;             // other is copy-constructed from b1.
b2 = std::move#include <utility>(b1);  // other is move-constructed from b1.

References