Reading the laws carefully:
20.2.2 swap [utility.swap]
- template void swap(T& a, T& b) noexcept(is_nothrow_move_constructible::value &&
is_nothrow_move_assignable::value);
2 Requires: Type T shall be MoveConstructible and MoveAssignable. (Table 20) and (Table 22)
3 Effects: Exchanges values stored in two locations.
- template void swap(T (&a)[N], T (&b)[N]) noexcept(noexcept(swap(*a, *b)));
4 Requires: a[i] shall be swappable with b[i] for all i in the range [0,N). (17.6.3.2)
5 Effects: swap_ranges(a, a + N, b)
25.3.3 swap [alg.swap]
- template void iter_swap(ForwardIterator1 a, ForwardIterator2 b);
5 Effects: swap(*a, *b).
6 Requires: a and b shall be dereferenceable. *a shall be swappable with *b. (17.6.3.2)
Thus iter_swap is required to exchange the values stored in two dereferenced locations or ranges of dereferenced locations, and any attempt to exchange the references or locations themselves is fighting against conformance. That clearly disables speculating about optimizations being the reason lying behind std::iter_swap. Instead, as Potatoswatter was properly pointing out, encapsulation and abstraction are the main reasons of its existence. std::iter_swap and std::swap each belong to diferent abstraction layers, the same way std::swap itself and any binary non-member function named "swap" selected via overload resolution differ.
Swap developer and designer roles to understand achieving the same result does not mean being the same, as in "even declaring a typedef from a fundamental type is just noise for a compiler, it is not noise for the reader". Take it as a joke, but we could argue whole C++ is just a deprecatable artifact wraping C, since both do the same thing while in the lowest level, and so on with any code block representing abstraction from another by means of a wrapper. Specially when the line is so thin as in the case of std::iter_swap, "swap" and std::swap. Maybe "using std::swap" has only a few caracters and it disappears once compiled, but means injecting an identifier and building a whole overload resolution mechanism. Injected over and over, built over and over, replaced over and over, discarded over and over. Far from an abstract, encapsulated and recycled approach.
Exposing the inner work trought the upper layer gives and aditional potential chance of failure on maintenance. In the swap domain, missing (or messing) a "using std::swap" on a deep metaprogramming containment design will silently wait inside your template function, waiting for a trivially swappable, fundamental or c-array type to break the build, if lucky, or even StackOverflow(TM) by means of infinite recursion. Obviously implementation of an extensible mechanism has to be published, but also has to be respected. About trivially swappable, mind anything moveconstructible and moveassignable is swappable against its own type even if it lacks of an overloaded swap resolution hook, and indeed there are obscure techniques to disable unwanted swappable behaviors.
With that on mind, maybe it all can be resumed in an unproper interpretation of the std::iter_swap identifier itself: it does not stand for "iterator swapping", but "iterable swapping". Don't be fooled by the standard requirements on arguments being forward iterators: in essence, a pointer is a random access iterator, thus satisfying the requirements. Phisically u pass by pointer, logically u pass by iterator. The commission usually tries to specify the minimal requirements for a facility to work with defined and expected behavior, nothing more. The "iterable swapping" name rightly exposes the goal and powers of the mechanism. the "std::iter_swap" identifier seems not due to confusion generated, but it is too late to change it and undo all the codebase relying on.
Feel free to swap as u wish as long as it works, but please not on my watch. Mixing abstraction layers won't make the compiler cry, but interfaces are just too cool to avoid. Instead, here is a snippet to help guidance in the future:
//#include <utility> // std::swap is not required here
#include <algorithm> // std::iter_swap is
namespace linker {
class base {
};
class member {
};
template<class M = member, class B = base> // requires swappable base and member
class link : B {
public:
void swap(link &other) { // using iterable swapping
std::iter_swap(static_cast<B*>(this), static_cast<B*>(&other));
std::iter_swap(&_member, &other._member);
}
private:
M _member;
};
template<class base, class member>
void swap(link<base,member>& left, link<base,member>& right) { // extending iterable swapping
left.swap(right);
}
}
namespace processor {
template<class A, class B>
void process(A &a, B &b) { // using iterable swapping
std::iter_swap(&a, &b);
}
}
int main() {
#if !defined(PLEASE_NO_WEIRDNESS)
typedef
linker::link<
linker::link<
linker::link< int[1] >,
linker::link< void*, linker::link<> >
>[2],
linker::link<
linker::member[3]
>
>
swappable[4]; // just an array of n-ary hierarchies
#else
typedef linker::link<> swappable;
#endif
swappable a, b;
processor::process(a, b);
}
Some points of interest as aditional guidance:
Swapping means thrown exceptions. Statement seems stupid, but it isn't once u know swap idiom is not focused on performance but on extreme safety and robustness.
std::iter_swap showcase one of the many lovely but overlooked features of metaprogramming: a template not only does overload resolution but also namespace resolution, allowing its use as the first in a chain of unknown and unrelated namespaces. Thanks, one thing less to worry about.
Swappable requirements allows u to use std::swap directly if (and
ONLY IF) u can afford making the assumption of both targets being of
fundamental or c-array to fundamental types, thus allowing the
compiler to bypass any overload resolution. Sadly that rules out the
parameters of almost every template. Using std::swap directly implies
both targets are of the same type (or forced to be of the same type).
Don't waste efforts on declaring swapable capabilities on a type wich
already is trivially swappable with itself, just like our link template
class (try removing linker::swap, behavior won't change at all).
“swap” was designed to be extensible to swap from diferent types,
automatic for same types. Mind a type is not "swappable" or
"non-swappable" by itself, but "swappable-with" or
"non-swappable-with" another type.
Finally, I wonder how many readers will notice
and recognize an utility is not an algorithm. In the Microsoft-Dinkumware implementation, among others, std::iter_swap just lives in the wrong header for convenience, wich isn't wrong. Maybe just it's identifier is.
Edit: After being faced with some more related mistakes, tought i could sumarize them like this: an algorithm is a concept so generic and specific, every time someone is about to specialize one of them, a designer cries somewhere else. In the case of std::iter_swap, since commitee clearly gives no freedom, any attempt to tweak the algorithm as in the relinking speculations would deserve a different meaning and identifier. Also maybe someone missed containers do have a swap member function, where optimizations do apply.
Better refactor so your final layer objects are nondata, fundamental, or represent hidden heavier objects (streamed if heavy enough). Embrace that resource adquisition should be initialization (RAII) and both new-delete overloads and container allocators have a use, to unleash true swap benefits with zero aditional effort. Optimize resources so u move data only on readquisition, then let C++ design your types easy, safe and fast by default.
Motto: Back in the old days, people struggled with data that was too fat on memory, too slow on disk. Nowadays, iterator vectors are filtered from storage pools, and streamed to be processed in parallel pipes. Tomorrow cars will drive alone. Deserves a PostIt.
iter_swap
can never relink the nodes of a linked list, because then a user holding an iterator into the linked list would see the contents swapped withswap(*a, *b)
, but not withiter_swap(a, b)
, which runs counter to the requirement thatiter_swap(a, b)
must behave likeswap(*a, *b)
. Now, whether that's desirable is an entirely different question...std::iter_swap
for this special kind of iterator, rather that overloading an artificialstd::swap
for values or r-value arguments.iter_swap
ericniebler.com/2015/02/03/iterators-plus-plus-part-1