C++核心准则C.89:保证哈希不会抛出异常

共 688字,需浏览 2分钟

 ·

2020-01-23 23:24

b4c63993e910c9ecaa0f630b59018c25.webp

白云母晶簇

7775d707a3688d47ecd98ac50022c262.webp

C.89: Make a hash noexcept

C.89:保证哈希不会抛出异常

c78ee9e9001e718f797d10e3338ad75b.webp


884de63f0d2941c0fcff7ae03be01d2b.webp7bfacf38fead3671c0b7d12e55d99348.webpReason(原因)7bfacf38fead3671c0b7d12e55d99348.webp

Users of hashed containers use hash indirectly and don't expect simple access to throw. It's a standard-library 

requirement.

哈希容器的用户间接地使用哈希功能,不希望简单的操作发生异常。这是标准库的要求。


884de63f0d2941c0fcff7ae03be01d2b.webp7bfacf38fead3671c0b7d12e55d99348.webpExample, bad(反面示例)7bfacf38fead3671c0b7d12e55d99348.webp
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.

如果你已经定义了哈希特化,争取简单地实现为通过异或和标准库哈希特化的组合。

884de63f0d2941c0fcff7ae03be01d2b.webp7bfacf38fead3671c0b7d12e55d99348.webpEnforcement(实现建议)7bfacf38fead3671c0b7d12e55d99348.webp
  • Flag throwing hashes.

  • 提示抛出异常的哈希。

884de63f0d2941c0fcff7ae03be01d2b.webp7bfacf38fead3671c0b7d12e55d99348.webp原文链接7bfacf38fead3671c0b7d12e55d99348.webp

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c89-make-a-hash-noexcept




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

浏览 33
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报