2015-08-18 51 views
0

我最近寫了代碼(相關的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

對我來說,感覺有點......根據指定......爲了我的代碼的正確行爲,它的交換操作必須具有與複製(移動)構造和複製(移動)分配的組合相同的語義。

我很清楚,實際的實現(使用複製後跟多個賦值)比應用交換到任何兩個元素進行排序要有效得多。

+0

這聽起來像是'std-discussion'的問題,而不是SO。 –

回答

1

當然。請參閱issue LWG 226paper N1523

一個主要問題正是要調用的內容。 ::std::swap不能超載,並且不合格swap可能不是正確的功能。事實上,金融行業一直是C++的主要用戶,對他們來說swap很可能是swap

相關問題