In C++, how does copy-and-swap implement Image's assignment operator, what guarantee does it give, and what does it cost compared with member-wise assignment?
answer
- take the parameter by value
- swap with a noexcept swap
- the old state dies with the parameter
- strong guarantee, extra allocation
basics
~20 sCopy-and-swap takes the source by value, swaps *this with that parameter through a non-throwing swap, and lets the parameter's destructor free the old state. Assignment fully succeeds or leaves *this unchanged, but always builds a complete copy.
solid answer
~50 sThe idiom writes one operator: `Image& operator=(Image other) noexcept { swap(*this, other); return *this; }`. Passing by value makes the caller build `other`: by copying from an lvalue, by moving from an rvalue, or directly from a prvalue. If that copy throws, it throws before the operator runs, so `*this` is untouched. The `noexcept` `swap` exchanges two members and cannot fail, and `other`'s destructor then frees the old buffer. The result is the **strong guarantee**, correct self-assignment without a check, and one function serving as both copy and move assignment. The costs: every copy assignment allocates a new buffer even when `*this` already has enough capacity, which `std::vector`'s own copy assignment can avoid; a self-assignment still copies everything; and because a by-value `operator=` counts as a user-declared copy assignment, the move constructor must be declared explicitly. Defining another `operator=(Image&&)` beside it makes `a = std::move(b)` ambiguous.
code
cpp · 30 lines#include <algorithm>
#include <cstddef>
#include <utility>
class Image {
public:
explicit Image(std::size_t n) : size_(n), pixels_(new unsigned char[n]{}) {}
Image(const Image& o) : size_(o.size_), pixels_(new unsigned char[o.size_]) {
std::copy(o.pixels_, o.pixels_ + size_, pixels_);
}
Image(Image&& o) noexcept
: size_(std::exchange(o.size_, 0)), pixels_(std::exchange(o.pixels_, nullptr)) {}
Image& operator=(Image other) noexcept { // copy or move happens in the parameter
swap(*this, other); // cannot throw
return *this; // other's destructor frees the old buffer
}
~Image() { delete[] pixels_; }
friend void swap(Image& a, Image& b) noexcept {
std::swap(a.size_, b.size_);
std::swap(a.pixels_, b.pixels_);
}
private:
std::size_t size_;
unsigned char* pixels_;
};
int main() {
Image a(16), b(64);
a = b; // copy into the parameter, then swap
a = Image(8); // parameter initialised from the prvalue, no copy
}go deeper
Recall the shape: take the argument by value, swap with it, and let the parameter's destructor release the old state.
Explain why the copy happening before the swap gives the strong guarantee and makes self-assignment safe without a check.
Weigh the strong guarantee against the allocation on every copy, declare the move constructor it forces, and avoid adding a second move assignment.
Decide where the strong guarantee is worth an allocation per assignment, and prefer rule-of-zero members where the basic guarantee suffices.
## The idiom **Copy-and-swap** writes the assignment operator in terms of the copy constructor, the move constructor, the destructor and a `swap` function, so the hard work lives in code that already exists: ```cpp Image& operator=(Image other) noexcept { // 1. parameter built by the caller swap(*this, other); // 2. exchange representations return *this; // 3. other's destructor frees the old state } friend void swap(Image& a, Image& b) noexcept { std::swap(a.size_, b.size_); std::swap(a.pixels_, b.pixels_); } ``` Step by step: 1. **The parameter is built by value.** `a = b;` copy-constructs `other` from `b`; `a = std::move(b);` move-constructs it; `a = Image(8);` initialises it directly from the prvalue. 2. **The swap cannot throw.** It exchanges a size and a pointer. 3. **The destructor cleans up.** `other` now holds `a`'s old buffer and frees it when the function returns. ## What it guarantees | Property | How copy-and-swap provides it | |---|---| | **Strong exception guarantee** | the only operation that can throw, the copy, runs before `*this` is touched | | **Self-assignment safety** | `a = a` copies first, then swaps with the copy; nothing is freed early | | **One operator for copy and move** | the caller's choice of copy or move constructor builds the parameter | | **No duplicated cleanup code** | freeing the old state is the destructor's job | The strong guarantee means the assignment either completes or leaves `*this` exactly as it was; the general vocabulary of basic, strong and nothrow guarantees belongs to the material on exception safety. The `noexcept` on the operator is honest because, as the standard specifies, the initialisation of each parameter occurs within the context of the full-expression where the function call appears: a `std::bad_alloc` from copying `b` is thrown in the caller, before the operator's body starts. ## What it costs - **No reuse of existing storage.** Assigning a 640x480 image to another 640x480 image allocates a fresh buffer and frees the old one, where a hand-written assignment could copy pixels into the existing buffer. A `std::vector` member's own copy assignment can likewise reuse capacity, which copy-and-swap gives up. - **Self-assignment is safe but not free.** `a = a` copies the whole image. It is rare, so this usually does not matter. - **An extra move.** For rvalues, the parameter is move-constructed and then swapped, slightly more work than a dedicated move assignment. - **It shapes the class's special members.** A by-value `operator=(Image)` is a copy assignment operator by the standard's definition, so it is user-declared, and the implicit move constructor is not declared. The class must declare `Image(Image&&) noexcept` itself, as the code example does. - **It conflicts with a separate move assignment.** Declaring both `operator=(Image)` and `operator=(Image&&)` makes `a = std::move(b)` ambiguous; Apple clang 21 reports `use of overloaded operator '=' is ambiguous`. ## When to use it Copy-and-swap fits a class that manages a resource directly, where correctness and the strong guarantee matter more than the cost of an allocation per copy assignment. It is a good default inside a small resource-owning type. It is a poor fit when: 1. Assignment is on a **hot path** and the target usually has enough capacity, as with frame buffers reused every frame. 2. The class can follow the **rule of zero**: an `Image` holding `std::vector<unsigned char>` gets correct, capacity-reusing copy assignment and a cheap move assignment for free, with only the basic guarantee for copies. 3. The team needs the copy and move paths **tuned separately**. ## A hand-written alternative If performance matters and the strong guarantee does not, write two operators: a copy assignment that reuses the buffer when sizes match and otherwise allocates the new buffer before releasing the old one, and a `noexcept` move assignment. That is more code to review, which is exactly the trade copy-and-swap avoids. ## Where the swap comes from The `swap` used inside the operator must be **non-throwing and member-wise**. Calling `std::swap(*this, other)` on the whole object is wrong: the generic `std::swap` requires move assignment, libc++ implements it as one move construction and two move assignments, and move assignment is the operator being defined, so it would recurse. A `friend void swap(Image&, Image&) noexcept` that swaps each member also lets generic code find it through argument-dependent lookup, the conventional way to make `using std::swap; swap(a, b);` use the type's own version. ## How to answer Show the three-line operator, explain why the copy happens before `*this` changes, list the guarantees, then name the costs: the unconditional copy, the declared move constructor it forces, and the ambiguity with a second move assignment.
- In C++, why can a copy-and-swap operator=(Image other) be marked noexcept when copying an Image can throw std::bad_alloc?The copy happens while initialising the parameter, and the standard says each parameter is initialised in the context of the full-expression where the call appears. So `std::bad_alloc` is thrown in the caller before the operator's body begins. Inside the body only the `noexcept` swap and a destructor run, so nothing can escape and `noexcept` is accurate.
- Does copy-and-swap still make sense for a C++ Image whose pixels live in a std::vector member?Usually not. With a `std::vector` member the class follows the rule of zero: the generated copy assignment reuses the vector's capacity when it can, and the generated move assignment is cheap and `noexcept`. Copy-and-swap would only add the strong guarantee for copy assignment, at the price of an allocation on every copy.
Copy-and-swap is like refitting a shop by building the new layout in an empty unit next door and then swapping the signs: if the builders fail halfway, the original shop is untouched, but you always pay for a whole second unit even when only one shelf changed.
- Copy-and-swap needs an explicit if (this != &other) check for self-assignment.
- Copy-and-swap is always the fastest way to write assignment.
- The by-value operator= suppresses nothing, so the implicit move constructor is still generated.
- Adding operator=(Image&&) next to operator=(Image) makes moves faster.
- std::swap on the whole object is a fine swap implementation for copy-and-swap.