C++ 命名要求: ValueSwappable (自 C++11 起)
来自 cppreference.cn
此类型的两个对象可以被解引用,并且在 std::swap 和用户定义的 swap() 都可见的上下文中,可以使用非限定函数调用 swap() 交换得到的值。
[编辑] 要求
如果类型 T 满足 ValueSwappable,则
-
T
满足 LegacyIterator 的要求。 - 对于类型 T 的任何可解引用对象 x(即,除结束迭代器之外的任何值),*x 满足 Swappable 的要求。
许多标准库函数期望它们的参数满足 ValueSwappable,这意味着任何时候标准库执行交换,它都使用等效于 using std::swap; swap(*iter1, *iter2);。
[编辑] 示例
运行此代码
#include <iostream> #include <vector> class IntVector { std::vector<int> v; // IntVector& operator=(IntVector); // not assignable (C++98 way) public: IntVector& operator=(IntVector) = delete; // not assignable void swap(IntVector& other) { v.swap(other.v); } }; void swap(IntVector& v1, IntVector& v2) { v1.swap(v2); } int main() { IntVector v1, v2; // IntVector is Swappable, but not MoveAssignable IntVector* p1 = &v1; IntVector* p2 = &v2; // IntVector* is ValueSwappable std::iter_swap(p1, p2); // OK: iter_swap requires ValueSwappable // std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable }
[编辑] 参见
(C++20) |
指定两个 indirectly_readable 类型引用的值可以被交换 (概念) |