Copy-swap is a C++ idiom that leverages the copy constructor and swap function to create an assignment operator. It follows a simple, yet powerful paradigm: create a temporary copy of the right-hand side object, and swap its contents with the left-hand side object.
Here's a brief summary:
Here's a code example for a simple String class:
class String {
// ... rest of the class ...
String(const String& other);
friend void swap(String& first, String& second) {
using std::swap; // for arguments-dependent lookup (ADL)
swap(first.size_, second.size_);
swap(first.buffer_, second.buffer_);
}
String& operator=(String other) {
swap(*this, other);
return *this;
}
};
Using the copy-swap idiom:
This approach simplifies the implementation and provides strong exception safety, while reusing the copy constructor and destructor code.