std::iter_swap 需要 ValueSwappable args vs std::swap 需要 Move A

std::iter_swap requires ValueSwappable args vs std::swap requires Move Assignable args

本文关键字:std swap 需要 Move vs args iter ValueSwappable      更新时间:2023-10-16

我很难理解为什么在下面的代码中直接调用std::swap()会导致编译错误,而使用std::iter_swap编译没有任何错误。

iter_swap()swap() - 有什么区别?,iter_swap最终打电话给std::swap但他们的行为仍然不同。

#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()
}

iter_swap 内部调用的swap不是完全限定的,即不称为std::swap,而是swap。因此,在名称查找和ADL编译器会找到多个与调用swap匹配的函数。但是,overload resolution会选择您提供的swap,因为它最匹配。

如果您在主代码中使用swap,那么它会编译得很好,因为它找不到std::swap。即使您执行using namespace std;,它也会编译