理由/讨论为什么std :: sort不被强制使用std :: swap

时间:2015-08-18 23:23:05

标签: c++ stl language-lawyer

我最近编写了代码(相关SO answerassociated code),其交换操作旨在具有与复制构造和复制分配的组合不同的语义。这就是我认识到std::sort并不总是使用std::swap或通过ADL找到的任何swap函数的地方。

对于那些不熟悉这一点的人,我把a small example

放在一起
#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;
}

现在 <{em> std::sort并非始终使用std::swap的事实已在SO上多次解决:

我的问题是:在提案或讨论方面是否有任何考虑强制std::sort(和类似的标准库函数)实际使用std::swap

对我而言,感觉有点......在指定的...下,对于我的代码的正确行为,它的交换操作必须具有与复制(移动)构造和复制(移动)分配的组合相同的语义。

我很清楚实际实现(使用副本后跟多个赋值)比将swap应用于任何两个元素进行排序要有效得多。

1 个答案:

答案 0 :(得分:1)

当然。请参阅issue LWG 226paper N1523

一个主要问题是究竟要拨打什么。 ::std::swap无法重载,不合格的swap可能不是正确的功能。事实上,金融行业一直是C ++的主要用户,对他们来说swap可能很好swap