What is the hash of a disabled std :: optional <T> object?

This page from cppreference indicates that std::hash was specialized for std::optional , but does not define behavior when an object is disabled. I can think of different behaviors:

  • It can throw std::bad_optional_access to match std::optional::value
  • It can return the same hash for each freed std::optional<T> , so 2 disconnected objects will have the same hash.
  • It can return std::optional<std::hash<std::optional<T>>>
+7
c ++ standard-library hash c ++ 14 optional
source share
2 answers

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

For an object o type optional<T> , if bool(o) == true , hash<optional<T>>()(o) will be evaluated with the same value as hash<T>()(*o) .

Thus, I would say that it is not indicated what the hash function returns for the disconnected object.

+6
source share

I'm not sure if this is relevant since C ++ 14 does not have std::optional in the long run. The intention (although not originally reflected in the standard standard) has always been that the hash of the freed optional object returns an undefined value, as Jonathan said.

This intention is reflected in the Fundamentals of TS .

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

+1
source share

All Articles