4

I am having difficulty in understanding why direct call to std::swap() in below code results in compilation error whereas using std::iter_swap compiles without any error.

From iter_swap() versus swap() -- what's the difference?, iter_swap finally calls std::swap but still their behavior is different.

#include <iostream>
#include <vector>

class IntVector {
    std::vector<int> v;
    IntVector& operator=(IntVector); // not assignable
public:
    void swap(IntVector& other) {
        v.swap(other.v);
    }
};
void swap(IntVector& v1, IntVector& v2) {
    v1.swap(v2);
}

int main()
{
    IntVector v1, v2;
//  std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable
    std::iter_swap(&v1, &v2); // OK: library calls unqualified swap()
}
JFMR
  • 23,265
  • 4
  • 52
  • 76
sbhal
  • 145
  • 10

1 Answers1

5

The swap called inside iter_swap is not fully qualified i.e not called as std::swap but just as swap. Therefore, during name lookup and ADL compiler finds multiple functions which matches with the call to swap. But, the overload resolution selects the swap provided by you since it matches best.

If you use swap in your main code, then it would compile fine as it would not find std::swap. It will compile even if you do using namespace std;

Arunmu
  • 6,837
  • 1
  • 24
  • 46
  • 5
    things like `swap`, `begin`, `size`... should be called unqualified, with `std::` version brought in current scope with using-declaration. Qualified call to those should be threated as bug on any code review. – Revolver_Ocelot Jul 10 '16 at 12:44