☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

与标准库相关的 hash 过程不应抛出异常

7.14 ID_throwInHash
目录 › next › previous

在对象的 hash 过程中不应抛出异常,否则相关的容器和算法无法正常工作。

示例:

struct U {   // User defined type
    int* p;
};

template <> struct std::hash<U> {   // Hash specialization
    using argument_type = U;
    using result_type = size_t;

    size_t operator()(const U& u) const {
        if (!u.p) {
            throw Exception();   // Non-compliant
        }
        return hash<int*>()(u.p);
    }
};

标准库规定容器的 find、count 等方法应通过返回值表示对象存在与否,然而如果 hash 过程抛出异常,这些方法也会抛出异常,相当于打破了这种约定,易造成意料之外的结果。

参考

C++ Core Guidelines C.89
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.