Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>>>
like image 762
qdii Avatar asked Oct 02 '13 08:10

qdii


People also ask

What is std :: optional C++?

(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.

Does STD optional allocate?

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 .


2 Answers

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.

like image 116
Jonathan Wakely Avatar answered Dec 21 '22 05:12

Jonathan Wakely


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.

like image 35
Andrzej Avatar answered Dec 21 '22 05:12

Andrzej