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:
- It reuses the copy constructor, so there's no duplicated copying code.
- Self-assignment is automatically safe.
- If the copy throws (runs out of memory),
*thisis untouched. That's called the strong exception guarantee.
Your turn: write the member swap and the copy-and-swap operator=.