Should the Copy-and-Swap Idiom become the Copy-and-Move Idiom in C++11?

First of all, it is generally unnecessary to write a swap function in C++11 as long as your class is movable. The default swap will resort to moves: void swap(T& left, T& right) { T tmp(std::move(left)); left = std::move(right); right = std::move(tmp); } And that’s it, the elements are swapped. Second, based on this, the … Read more

When is overloading pass by reference (l-value and r-value) preferred to pass-by-value?

For types whose copy assignment operator can recycle resources, swapping with a copy is almost never the best way to implement the copy assignment operator. For example look at std::vector: This class manages a dynamically sized buffer and maintains both a capacity (maximum length the buffer can hold), and a size (the current length). If … 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