AutosarC++17_10-A18.1.6

All std::hash specializations for user-defined types shall have a noexcept function call operator

Required inputs: IR

Rationale

Some of standard library containers use std::hash indirectly. Function call operator should be defined as noexcept to prevent container simple access from throwing an exception.

Note: Consider own hash specializations to use standard library specializations combined with XOR (ˆ) operation.

Example
// $Id: A18-1-6.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <functional>
#include <iostream>

class A {
public:
  A(uint32_t x, uint32_t y) : x(x), y(y) {}

  uint32_t GetX() const { return x; }
  uint32_t GetY() const { return y; }

private:
  uint32_t x;
  uint32_t y;
};

class B {
public:
  B(uint32_t x, uint32_t y) : x(x), y(y) {}

  uint32_t GetX() const { return x; }
  uint32_t GetY() const { return y; }

private:
  uint32_t x;
  uint32_t y;
};

namespace std {
// Compliant
template <> struct hash<A> {
  std::size_t operator()(const A &a) const noexcept {
    auto h1 = std::hash<decltype(a.GetX())>{}(a.GetX());
    auto h2 = std::hash<decltype(a.GetY())>{}(a.GetY());
    return h1 ^ (h2 << 1);
  }
};
// Non-compliant
template <> struct hash<B> {
  std::size_t operator()(const B &b) const {
    if (b.GetX() > 5) {
      throw std::runtime_error("B class hash operator exception");
    }

    auto h1 = std::hash<decltype(b.GetX())>{}(b.GetX());
    auto h2 = std::hash<decltype(b.GetY())>{}(b.GetY());
    return h1 ^ (h2 << 1);
  }
};
} // namespace std

int main() {
  A a(5, 7);
  A aa(1215, 545467);
  B b(3, 1);
  B bb(121, 17);

  try {
    std::cout << std::hash<A>{}(a) << " " << std::hash<A>{}(aa) << std::endl;
    std::cout << std::hash<B>{}(b) << std::endl;
    std::cout << std::hash<B>{}(bb) << std::endl;
  } catch (const std::runtime_error &e) {
    std::cout << e.what() << std::endl;
  }

  return 0;
}
See Also
  • C++ Core Guidelines [10]: C.89: Make a hash noexcept.

Possible Messages

Key

Text

Severity

Disabled

specialization_of_hash_except

std::hash specialization shall have noexcept call operator.

None

False

Options