How to implement swap()?

Viewed 12096

Possible Duplicate:
how to provide a swap function for my class?

Every time I think I understand it, I see something that really confuses me.

If you want to provide an implementation of swap for your own class, what do you do?

The list of possibilities is:

  1. Define one inside the std namespace (taking two arguments), which calls #3 below
    (some say this is correct; some people say illegal)

  2. Define a static method inside the class, taking two arguments to swap
    (makes more sense to me than #4, but I don't get why no one does this), which calls any base-class swaps as necessary

  3. Define an instance method inside the class, taking one other argument to swap with, which calls any base-class swaps as necessary

  4. Define an instance method inside the class, taking two other arguments to swap, also here, which calls any base-class swaps as necessary

  5. Define one in your own namespace (taking two arguments), which calls #3

  6. Something else

My own understanding is that I need #5 and #3, where the caller would then be calling swap likeusing std::swap; swap(a, b);,but the fact that no one seems to suggest that combination is really confusing me. And I really don't understand #4 at all, because everyone seems to be using an instance member when in fact the operation is static. I can't tell if my understanding is wrong or a bunch of the answers I see when looking this up.

What's the correct way?

3 Answers
Related