2016-02-22 79 views
4

std::not1()的原型如下:爲什麼std :: not1()通過const引用而不是通過值引用參數?

template< class Predicate > 
std::unary_negate<Predicate> not1(const Predicate& pred); 

這有效地禁止移動語義。爲什麼沒有原型如下:

template< class Predicate > 
std::unary_negate<Predicate> not1(Predicate pred); 

這種方式,複製或移動取決於pred是如何構建的。該功能只是將pred移動到構造的std::unary_negate對象。

+3

他們可以爲rvalues添加額外的重載,但是當你有lambda時,沒有人真正關心那些非泛型助手。無論如何,他們很快就會取代接受'not_fn'的普遍引用。 –

+0

@ hvd剛剛刪除'constexpr'並回退到C++ 03。 – Lingxi

+0

@靈溪對我來說這似乎完全合理,謝謝。 – hvd

回答

5

單獨做出這種改變是完全沒有用的。 not1所做的是使用pred作爲構造函數的參數構造std::unary_negate<Predicate>。但std::unary_negate<Predicate>唯一相關的構造函數需要const Predicate &,而不是Predicate &&

邏輯後續問題將是,爲什麼std::unary_negate<Predicate>有一個構造函數採取Predicate &&?在設計時顯然不可能採取這樣的論點,因爲右值引用還不存在。至於以後,這只是一個猜測,但我認爲lambda已經很好地滿足了需求,所以unary_negate沒有太多意義,除了向後兼容性。

+0

聽起來很合理。不過,我更喜歡'std :: not1()'給lambda,因爲它的語法更簡單,更直觀,更可讀。 – Lingxi

+0

@Lingxi如果標準庫是從頭開始設計的,我想'std :: not1'可能被定義爲返回一個未指定的返回類型,所以可以通過返回一個lambda來實現。 :)不幸的是,現在做出這種改變也會打破向後兼容性。 – hvd

相關問題