Why is std::hash not guaranteed to be deterministic?

前端 未结 2 860
不思量自难忘°
不思量自难忘° 2020-12-29 20:52

Hereafter, we use N4140 (C++14 Standard).


According to § 17.6.3.4 Hash requirements,

The value returned shall depend only on t

2条回答
  •  时光取名叫无心
    2020-12-29 21:32

    There is no need for the hash function to be deterministic between runs, but you can still provide your own hash, e.g. for unordered containers if it's a behavior you rely on.

    As for why, cppreference says:

    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 denial-of-service attacks.

    If the Hash requirements tells it to be deterministic, then you wouldn't be able to provide a salted hash without breaking the requirement.

    Here is the actual explanation why

提交回复
热议问题