You can provide your own hash function when using a standard library container based on a hash table (for instance,
std::unordered_map
). One of the requirements of the hash function is that it should not throw exceptions.
If you don’t follow this requirement and your hash function throws, you may end up with corrupted data in your container.
Since this function is not supposed to throw, you should also declare it noexcept
.
Noncompliant code example
struct MyHash {
size_t operator() (Customer c) const { // Noncompliant, copying may throw
if (c.name().empty()) {
throw std::runtime_error("You should know the customer name at this point"); // Noncompliant
}
return std::hash<std::string>()(c.name());
}
};
std::unordered_set<Customer, MyHash> mySet;
Compliant solution
struct MyHash {
size_t operator() (Customer const &c) const noexcept {
return std::hash<std::string>()(c.name());
}
};
std::unordered_set<Customer, MyHash> mySet;