Considering the advantages of copy-and-swap idiom...
Why do we still need copy-assignment operator accepting references as the mainstream?
class T {
public:
// 1: Why still commonly this?
T& operator=(const T& rhs);
// 2: Why not mostly that?
T& operator=(T rhs);
}
There are answers suggesting to use the latter (here and here).
However, most of the SO examples are still around pass-by-reference operator=
.
Even consolidated C++ FAQ points out (yes, it's about const
, but...):
A
class Fred
’s copy constructor and assignment operator should haveconst
in the parameter: respectivelyFred::Fred(const Fred&)
andFred& Fred::operator=(const Fred&)
Obviously, copy-and-swap is implementable via pass-by-reference - it is just unnecessary if copy is to be made anyway. One may also want to avoid copying immediately on call (perform it conditionally in the body) - isn't that the less frequent case (possibly premature optimization) then?
Shouldn't copy-and-swap with pass-by-value assignment be the default approach?