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:
std::bad_optional_access
, to be consistent with std::optional::value
std::optional<T>
, this way 2 disengaged object would have the same hash.std::optional<std::hash<std::optional<T>>>
(since C++17) The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
What's more, std::optional doesn't need to allocate any memory on the free store. std::optional is a part of C++ vocabulary types along with std::any , std::variant and std::string_view .
The C++14 CD said in [optional.hash]/3:
For an object
o
of typeoptional<T>
, ifbool(o) == true
,hash<optional<T>>()(o)
shall evaluate to the same value ashash<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With