Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C++ std::hash implementations always deterministic?

Tags:

c++

std

hash

I know that std::hash<T> are implementation dependent, but are they supposed to be deterministic?

I know if I ran the std::hash<T> function on a value in the same process multiple times, I would get the same output. However, if I restarted the process, would I get the same value? Is there a seed that is used for std::hash? Does it depend on the compiler version, or some other factor?

Is there a guarantee that with an input X I will always get output Y regardless of when the process running was started, the machine, or the compiler version?

like image 402
ajoseps Avatar asked Dec 17 '25 10:12

ajoseps


2 Answers

No, and documentation clearly says that:

Hash functions are only required to produce the same result for the same input within a single execution of a program; this allows salted hashes that prevent collision DoS attacks.

emphasis is mine. This is since C++14, but we cannot assume that it would work C++11 as such guarantee was not provided explicitly.

like image 134
Slava Avatar answered Dec 20 '25 00:12

Slava


Enabled specializations of std::hash satisfy the Hash requirements ([hash.requirements]), according to which

The value returned shall depend only on the argument ... for the duration of the program.

There is no guarantee that hash values are stable across invocations, even if those invocations are of the same binary image on the same machine.

like image 34
Brian Bi Avatar answered Dec 20 '25 00:12

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!