Why do some people use swap for move assignments?

It’s my fault. (half-kidding, half-not). When I first showed example implementations of move assignment operators, I just used swap. Then some smart guy (I can’t remember who) pointed out to me that the side effects of destructing the lhs prior to the assignment might be important (such as the unlock() in your example). So I …

Read more

public friend swap member function

There are several ways to write swap, some better than others. Over time, though, it was found a single definition works best. Let’s consider how we might think about writing a swap function. We first see that containers like std::vector<> have a single-argument member function swap, such as: struct vector { void swap(vector&) { /* …

Read more

What is the copy-and-swap idiom?

Overview Why do we need the copy-and-swap idiom? Any class that manages a resource (a wrapper, like a smart pointer) needs to implement The Big Three. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls …

Read more