我最近寫了代碼(相關的SO answer,associated code),它們的交換操作打算具有與複製構造和複製分配的組合不同的語義。這就是我認識到std::sort
並不總是使用std::swap
或通過ADL發現的任何swap
函數。理由/討論爲什麼std :: sort不是被迫使用std :: 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;
}
現在是std::sort
並不總是使用std::swap
已討論多次,這裏SO事實:
我問題是:以前有任何考慮,在建議或討論的條款,迫使std::sort
(以及類似的標準庫函數)實際使用std::swap
?
對我來說,感覺有點......根據指定......爲了我的代碼的正確行爲,它的交換操作必須具有與複製(移動)構造和複製(移動)分配的組合相同的語義。
我很清楚,實際的實現(使用複製後跟多個賦值)比應用交換到任何兩個元素進行排序要有效得多。
這聽起來像是'std-discussion'的問題,而不是SO。 –