std::iter_swap 需要 ValueSwappable args vs std::swap 需要 Move Assignable args
std::iter_swap requires ValueSwappable args vs std::swap requires Move Assignable args
我很难理解为什么在下面的代码中直接调用 std::swap()
会导致编译错误,而使用 std::iter_swap
编译却没有任何错误。
从 iter_swap()
versus swap()
-- what's the difference? 开始,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;
它也会编译
我很难理解为什么在下面的代码中直接调用 std::swap()
会导致编译错误,而使用 std::iter_swap
编译却没有任何错误。
从 iter_swap()
versus swap()
-- what's the difference? 开始,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;