繁体   English   中英

理由/讨论为何不强制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的事实:

我的问题是:在建议或讨论方面,是否考虑过强制std::sort (和类似的标准库函数)实际使用std::swap

在我看来,在指定的条件下……对于我的代码的正确行为,它的交换操作必须具有与复制(移动)构造和复制(移动)分配的组合相同的语义。

我很清楚这样一个事实,即实际的实现(使用副本再进行多次分配)比对任何两个元素进行交换要有效得多。

绝对是 参见问题LWG 226N1523 文件

一个主要问题就是该怎么称呼。 ::std::swap不能重载,并且不合格的swap可能不是正确的功能。 实际上,金融业一直是C ++的主要用户,对他们而言, swap很可能是swap

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM