39

I was just wondering, why would anybody write this:

std::iter_swap(i, k);

instead of this?

std::swap(*i, *k);   // saved a few keystrokes!

Then I looked into the implementation of iter_swap, and of course it only uses swap instead of std::swap since we're already in namespace std, anyway. That leads me to the next question:

Why would anybody write this:

using std::swap;
swap(a, b);

instead of this?

std::iter_swap(&a, &b);   // saved an entire line of code!

Are there any important differences/issues I am overlooking here?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

2 Answers2

41

From the SGI docs (here):

[1] Strictly speaking, iter_swap is redundant. It exists only for technical reasons: in some circumstances, some compilers have difficulty performing the type deduction required to interpret swap(*a, *b).

sehe
  • 374,641
  • 47
  • 450
  • 633
12

To answer your second question, the using + swap allows the compiler to use user-defined swap functions that may be more efficient than the default implementation (by using ADL). Explicitly saying std::swap inhibits ADL and any custom swap methods it maybe have been able to find.

As for iter_swap it's presumably there to use in templates and clearly indicate intention rather than a swap that might indicate you expect a pointer.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • Oh I neglected this because I'm absolutely convinced Fred knows about ADL and std::swap idioms :) – sehe Dec 21 '12 at 14:45
  • There is no `std::swap` invocation in my second question. My point was that `std::iter_swap` will also pick up user-defined swaps, without having to write a `using` statement. Right? – fredoverflow Dec 21 '12 at 14:52
  • 1
    @FredOverflow: But not user-defined `iter_swap`s ;) – MSalters Dec 21 '12 at 16:17