1

If Coll is a standard container type, a and b are instances of Coll; then, should we ALWAYS use std::swap(a, b) instead of a.swap(b)?

For me, std::swap(a, b) is more generic than a.swap(b). However, I just wonder, can this be a best practice? or any counter example?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 1
    A counter example could be the pre-C++11 trick to release memory allocated by containers: `std::vector().swap(v);`. You cannot do this with `std::swap`, since it requires both arguments to be lvalues. – Daniel Langr Jul 24 '18 at 07:19
  • "more generic" is not necessarily a design goal. Engineering is about making design decisions that reflect the particular circumstances of the problem being solved, not blindly applying rules. Anyone can build a bridge that stands up; it takes an engineer to build one that barely stands up. – Pete Becker Jul 24 '18 at 12:09

1 Answers1

2

When there is a member swap function available, it makes sense to prefer it. Why should it exist in the first place, if it does nothing but duplicating the default std::swap implementation?

Beyond that, I would distinguish between standard containers and others. In the former case, std::swap is specialized to do the right thing for your container instance. In the latter case, go with the member swap function.

lubgr
  • 37,368
  • 3
  • 66
  • 117