In the standard library, if a class type has a specialized swap algorithm, then it will have a member function swap
and a free function swap
that simply forwards to the member function. I don't quite get the rationale behind having both of them (and thus code duplication) but not just the free function one. Note that, when I say the free function, I take to mean the specialized free swap function, not the generic std::swap
function template. Such a specialized function may have privileged access to the relevant class by being a friend of it.
I have two points to support just leaving the free function rather than the member function. First, it forms a more generic swap interface to facilitate writing generic algorithms, for non-class types like arrays cannot have member functions. Second, swap is a binary operation involving two operands and demonstrates a sense of symmetry. It's more natural and intuitive to perform swap using a free function that does not have bias on either operand. For this reason, I have always felt somewhat weird when using the member function swap
as if I was performing some operation that is based on the invoking object.