理由/讨论为什么 std::sort 不强制使用 std::swap
Justification/Discussion why std::sort isn't forced to use std::swap
我最近写了一段代码(相关的SO答案,关联代码),其交换操作的语义与复制构造和复制赋值的组合不同。这就是我认识到std::sort
并不总是使用std::swap
或通过ADL找到的任何swap
函数的地方。
对于那些不熟悉这个的人,我整理了一个小例子:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
namespace thing {
struct thing {
int dummy;
operator int (void) const {
return dummy;
}
thing (int value) : dummy (value) {}
thing (thing const & other) : dummy (other.dummy) {
cout << "copy " << this << " from " << &other << endl;
}
thing & operator=(thing const & other) {
dummy = other.dummy;
cout << "assign " << this << " from " << &other << endl;
}
void swap (thing & other) {
// not called
}
};
void swap (thing & lhs, thing & rhs) {
// not called
}
}
int main() {
vector<thing::thing> data = {1, 21, 42};
cout << "sorting now" << endl;
sort (begin (data), end (data), greater<int>{});
return 0;
}
现在 std::sort
并不总是使用std::swap
的事实已经在SO上解决了多次:
- std::sort并不总是调用std::swap
- STL排序使用交换或二进制拷贝?
我的问题是:在提案或讨论方面,是否考虑过强制std::sort
(和类似的标准库函数)实际使用std::swap
?
对我来说感觉有点……根据规定…为了使我的代码的正确行为,它的交换操作必须具有与copy (move)构造和copy (move)赋值的组合相同的语义。
我很清楚这样一个事实,实际的实现(使用副本和多个赋值)比对任意两个元素应用swap来排序要有效得多。
当然。见issue LWG 226和paper N1523
一个主要问题是该怎么称呼。::std::swap
不能重载,不限定的swap
可能不是正确的函数。事实上,金融行业一直是c++的主要用户,对他们来说,swap
可能是一个很好的交换。
相关文章:
- a,b = b,a in python vs std::swap() in C++
- 使用 std::swap 禁用 ADL
- 如何使用 std::swap with array?
- 智能指针的 std::swap 是否保证引用保持不变?
- "std::swap"应用于这些对象时会做什么?
- 为什么 std::swap 不使用 swap 习语?
- 为什么有这么多std::swap的专业化
- 为什么使用std::swap不会在外部范围中隐藏其他交换函数
- 在结构C++中使用 std::swap 与 std::vector
- 为什么 std::swap 不适用于地址运算符
- std::swap vs std::exchange vs swap operator
- 使用静态tmp变量为简单类型C++重新实现std::swap()
- 使用 GCC 4.8 编译时无法对向量执行 std::swap
- 可以将"using std::swap;"放在标题中吗?
- "using std::swap"如何启用 ADL?
- std::swap 在 VS 2013 中导致无限递归
- 为什么不是 std::swap 在全局命名空间中
- std::swap(*(void **)x, *(void **)y)y是什么意思
- 在向量之间使用 std::swap 或 vector::swap
- 为什么 std::swap 不适用于模板项