sbh*_*hal 4 c++ swap move-semantics c++11
我很难理解为什么直接调用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()
}
Run Code Online (Sandbox Code Playgroud)
在swap所谓的内部iter_swap是不完全合格的,即没有被称为std::swap只是作为swap.因此,在名称查找期间,ADL编译器会找到与调用匹配的多个函数swap.但是,overload resolution选择swap由您提供的最佳匹配.
如果你swap在主代码中使用它,它将编译好,因为它找不到std::swap.即使你这样做,它也会编译using namespace std;
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |