C++核心準則C.89:保證哈希不會拋出異常

白云母晶簇

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.
哈希容器的用戶間接地使用哈希功能,不希望簡單的操作發(fā)生異常。這是標準庫的要求。

Example, bad(反面示例)
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()(x.s.size()) ^ trim(x.s);
? ?}
};
int main()
{
? ?unordered_map m;
? ?My_type mt{ "asdfg" };
? ?m[mt] = 7;
? ?cout << m[My_type{ "asdfg" }] << '\n';
} 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.
如果你已經(jīng)定義了哈希特化,爭取簡單地實現(xiàn)為通過異或和標準庫哈希特化的組合。

Enforcement(實現(xiàn)建議)
Flag throwing hashes.
提示拋出異常的哈希。

原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c89-make-a-hash-noexcept
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
