C/C++ Arena

Step 6 of 8

Copy assignment with copy-and-swap

Copy assignment (a = b; on an existing a) is harder than the copy constructor: a already owns memory that must be released, and a = a; must not destroy itself.

The standard trick is copy-and-swap:

void swap(IntArray& other) noexcept {
    std::swap(data_, other.data_);
    std::swap(n_, other.n_);
}
IntArray& operator=(IntArray other) {   // by value: a copy is made here
    swap(other);                        // take the copy's guts
    return *this;                       // other's destructor frees our old data
}

Why professionals like it:

Your turn: write the member swap and the copy-and-swap operator=.

Previous: Non-copyable classes Next: The rule of zero