4

A textbook by Torsten T. Will on C++11 says that since C++11, std::swap will use a nonmember swap found by ADL if such a nonmember function is defined, thus the pattern

using std::swap;
swap (obj1, obj2);

can always be replaced by a simple

std::swap (obj1, obj2);

Unfortunately, I did not find such a statement anywhere else.

What is the truth?

JohnB
  • 13,315
  • 4
  • 38
  • 65
  • 2
    I doubt it's true, because if that nonmember `swap` is implemented via `std::swap` then there's infinite mutual recursion. Or worse, that `swap` function doesn't swap objects (but instead happens to do something totally unrelated, and just so happens to be named `swap` and takes two mutable references). But that's just my hunch; I have been known to be totally wrong at times. – Cornstalks Dec 29 '15 at 16:14

1 Answers1

6

From C++14 (or more specifically N4140):

Requires: Type T shall be MoveConstructible (Table 20) and MoveAssignable (Table 22). Effects: Exchanges values stored in two locations.

There is nothing here about calling non-member swap. So no, there are no guarantees that std::swap is implemented via non-member swap.

It's not entirely clear if an implementation would even be allowed to implement std::swap in terms of a user-defined, non-member ADL swap.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 3
    I'm not sure a particular implementation could (legally) do this. It assumes the non-member `swap` produces the desired effect (exchanging values of two objects). If the compiler could see the non-member `swap` implementation and if it was simple enough for the compiler to deduce that it does indeed swap objects, then I suppose it could call it. But I don't think the compiler can make any assumptions about non-trivial non-member `swap` functions, because it would not be clear if they really swapped the objects. – Cornstalks Dec 29 '15 at 16:24
  • Ok, then the textbook is wrong here. Generally, however, it's very good. – JohnB Dec 29 '15 at 16:24
  • @Cornstalks: That's a good point. – Nicol Bolas Dec 29 '15 at 16:34