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

网友投稿 249 2022-12-02

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.

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

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.

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

Enforcement(实现建议)

Flag throwing hashes.提示抛出异常的哈希。

原文链接

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

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++核心准则C.81:如果不需要默认(同时不需要其他选项)行为,使用=delete禁止它们
下一篇:Java SpringBoot 使用拦截器作为权限控制的实现方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~