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

Justification/Discussion why std::sort isn't forced to use std::swap

本文关键字:std swap sort 为什么 理由      更新时间:2023-10-16

我最近写了一段代码(相关的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可能是一个很好的交换。