Legacy C++ › 7. Idioms and Patterns
The Copy-and-Swap Idiom
Exception-safe assignment operators.
advanced #copy-and-swap#assignment#exception-safety#swap#idiom
Explanation
The copy-and-swap idiom implements the assignment operator in terms of the copy constructor and a non-throwing swap:
- Make a copy of the right-hand side (this is the only step that can throw).
- Swap the contents of
*thiswith the copy (cannot throw). - The copy’s destructor releases the old contents.
Benefits:
- Strong exception safety: if copying throws,
*thisis untouched. - Self-assignment is safe with no special
iftest. - No duplicated logic: the copy constructor and destructor do the real work.
Taking the parameter by value merges steps 1 and the copy: T& operator=(T other) { swap(other); return *this; }.
Example
#include <algorithm>
#include <cstring>
#include <iostream>
class Text {
char* data_;
std::size_t size_;
public:
explicit Text(const char* s = "")
: data_(0), size_(std::strlen(s)) {
data_ = new char[size_ + 1];
std::memcpy(data_, s, size_ + 1);
}
Text(const Text& o) : data_(0), size_(o.size_) { // copy constructor
data_ = new char[size_ + 1];
std::memcpy(data_, o.data_, size_ + 1);
}
~Text() { delete[] data_; }
void swap(Text& o) { // never throws
std::swap(data_, o.data_);
std::swap(size_, o.size_);
}
Text& operator=(Text other) { // by value: this IS the copy
swap(other);
return *this; // 'other' frees the old data
}
const char* c_str() const { return data_; }
};
int main() {
Text a("hello"), b("world");
a = b; // copy, swap
a = a; // self-assignment is fine
std::cout << a.c_str() << " " << b.c_str() << "\n"; // world world
return 0;
}
Common pitfalls
swapmust not throw (do not allocate in it); otherwise the guarantee is lost.- Provide a free
swap(T&, T&)in the same namespace sousing std::swap; swap(a, b);finds it through ADL. - It can be slower than a hand-tuned assignment that reuses existing capacity (e.g. assigning equal-sized buffers).
- Do not call the assignment operator from the copy constructor, or vice-versa.
- With a by-value parameter, the class must be copyable and cheap to copy-construct.
Legacy vs modern
C++11 adds move construction, so the same by-value operator= also serves as move assignment automatically when passed an rvalue. In practice, prefer the Rule of Zero: hold a std::string/std::vector/unique_ptr and write none of these. See Move Semantics and unique_ptr.
Exercises
1. Where does the old contents of *this get destroyed in operator=(Text other)?
After the swap, other holds the old data, and it is destroyed when the function returns.