C++ compilers automatically generate copy constructors and copy-assignment operators. Why not swap
too?
These days the preferred method for implementing the copy-assignment operator is the copy-and-swap idiom:
T& operator=(const T& other)
{
T copy(other);
swap(copy);
return *this;
}
(ignoring the copy-elision-friendly form that uses pass-by-value).
This idiom has the advantage of being transactional in the face of exceptions (assuming that the swap
implementation does not throw). In contrast, the default compiler-generated copy-assignment operator recursively does copy-assignment on all base classes and data members, and that doesn't have the same exception-safety guarantees.
Meanwhile, implementing swap
methods manually is tedious and error-prone:
- To ensure that
swap
does not throw, it must be implemented for all non-POD members in the class and in base classes, in their non-POD members, etc. - If a maintainer adds a new data member to a class, the maintainer must remember to modify that class's
swap
method. Failing to do so can introduce subtle bugs. Also, sinceswap
is an ordinary method, compilers (at least none I know of) don't emit warnings if theswap
implementation is incomplete.
Wouldn't it be better if the compiler generated swap
methods automatically? Then the implicit copy-assignment implementation could leverage it.
The obvious answer probably is: the copy-and-swap idiom didn't exist when C++ was developed, and doing this now might break existing code.
Still, maybe people could opt-in to letting the compiler generate swap
using the same syntax that C++0x uses for controlling other implicit functions:
void swap() = default;
and then there could be rules:
- If there is a compiler-generated
swap
method, an implicit copy-assignment operator can be implemented using copy-and-swap. - If there is no compiler-generated
swap
method, an implicit copy-assignment operator would be implemented as before (invoking copy-assigment on all base classes and on all members).
Does anyone know if such (crazy?) things have been suggested to the C++ standards committee, and if so, what opinions committee members had?