문제

This page from cppreference mentions that std::hash has been specialized for std::optional, but doesn’t specify the behavior when the object is disengaged. I can think of different behaviors:

  • It could throw a std::bad_optional_access, to be consistent with std::optional::value
  • It could return the same hash for every disengaged std::optional<T>, this way 2 disengaged object would have the same hash.
  • It could return a std::optional<std::hash<std::optional<T>>>
도움이 되었습니까?

해결책

The C++14 CD said in [optional.hash]/3:

For an object o of type optional<T>, if bool(o) == true, hash<optional<T>>()(o) shall evaluate to the same value as hash<T>()(*o).

So I would say it's unspecified what the hash function returns for a disengaged object.

다른 팁

I am not sure if it is relevant anymore, as C++14 does not have std::optional ultimately. The intention (although not reflected in the standardese initially) has always been that the hash of a disengaged optional object returns an unspecified value, as Jonathan said.

This intent is reflected in the Fundamentals TS.

The idea is that the implementation of the Standard Library chooses how it wants to represent a disengaged optional<T> and documents it itself. It can choose a different value for different types, and also a different value in debug and release mode.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top