C.89: Make a hash noexcept
C.89:保證哈希不會拋出異常
Reason(原因)
Users of hashed containers use hash indirectly and don't expect simple access to throw. It's a standard-library requirement.
哈希容器的用戶間接地使用哈希功能,不會希望簡單的操作發生異常。這是標準庫的要求。
Example, bad(反面示例)
<code>template<>struct hash{ // thoroughly bad hash specialization using result_type = size_t; using argument_type = My_type; size_t operator() (const My_type & x) const { size_t xs = x.s.size(); if (xs < 4) throw Bad_My_type{}; // "Nobody expects the Spanish inquisition!" return hash<size>()(x.s.size()) ^ trim(x.s); }};int main(){ unordered_map /<code>m; My_type mt{ "asdfg" }; m[mt] = 7; cout << m[My_type{ "asdfg" }] << '\\n';} /<size>
If you have to define a hash specialization, try simply to let it combine standard-library hash specializations with ^ (xor). That tends to work better than "cleverness" for non-specialists.
如果你已經定義了哈希特化,爭取簡單地實現為通過異或和標準庫哈希特化的組合。
Enforcement(實現建議)
- Flag throwing hashes.
- 提示拋出異常的哈希。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c89-make-a-hash-noexcept
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章