Table of Contents

C++ Copy-and-swap

Copy-and-swap is an idiom for implementing exception-safe copy assignment: copy the argument into a temporary, swap the temporary's contents with this object's, and let the temporary (holding the old data) be destroyed. This guarantees strong exception safety because the swap itself cannot fail.

Use copy-and-swap for copy assignment in classes managing resources to achieve strong exception safety guarantees.

Example

This example shows copy-and-swap providing exception-safe assignment.

// compile: g++ -o swap swap.cpp
// run: ./swap
// description: copy-and-swap idiom for exception-safe assignment
 
#include <iostream>
#include <utility>
 
class Buffer {
private:
    int* data;
    size_t size;
public:
    Buffer(size_t n = 0) : size(n) {
        data = new int[n];
    }
 
    ~Buffer() { delete[] data; }
 
    Buffer(const Buffer& other) : size(other.size) {
        data = new int[size];
        std::copy(other.data, other.data + size, data);
    }
 
    Buffer& operator=(Buffer temp) {  // take by value (copy happens in parameter)
        swap(*this, temp);            // swap (temp holds old data)
        return *this;
    }
 
    friend void swap(Buffer& a, Buffer& b) {
        using std::swap;
        swap(a.data, b.data);
        swap(a.size, b.size);
    }
};
 
int main() {
    Buffer b1(10), b2(20);
    b1 = b2;  // exception-safe: if copy fails, b1 unchanged
 
    return 0;
}