ajoseps
ajoseps

Reputation: 2121

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

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?

Upvotes: 3

Views: 2749

Answers (3)

David Culbreth
David Culbreth

Reputation: 2796

According to the c++ standard,

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.

Upvotes: 2

Brian Bi
Brian Bi

Reputation: 119382

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.

Upvotes: 4

Slava
Slava

Reputation: 44268

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.

Upvotes: 10

Related Questions