Is it a good general practice to always implement my copy assignment operators using std::swap
? My understanding is that this provides a way to share the copy constructor implementation. I'd like to avoid duplicating the actual copy logic itself. So here is what I'd do:
class Foo
{
public:
Foo(Foo const& other) { /* assume valid implementation */ }
Foo& operator= (Foo other)
{
std::swap(*this, other);
return *this;
}
};
The act of passing "other" into the assignment operator performs copy construction (we've shared the copy logic at this point). I assume the swap will invoke move construction (which has a compiler-generated implementation here).
I've been doing this to pretty much every class I implement copy construction for, since the assignment & constructor never have different implementations.