MSDN says:
swap
should be used in preference toiter_swap
, which was included in the C++ Standard for backward compatibility
You have hit on the key distinction.
swap(*a, *b)
is a global function that resets all pointers pointing to *a
to point to what was the contents of *b
and vice versa. It's the old tmp = a
, a = b
, b = tmp
swap.
iter_swap
is for the more limited case of modifying the underlying objects being iterated over to affect the structures of which they were a part. If *a
and *b
were part of the same linked list, it was sufficient for iter_swap
to simply swap their positions in the list. This is an advantage for when you want to simply sort a list without invalidating/changing external pointers to objects in the list. If I have a pointer to a user
object I don't care if you sort the list
of user
objects, I don't want my idea of who is the "current" user to change, so list sort better not use swap
.