Domanda

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>>>
È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top