简体   繁体   English

C ++ std :: hash实现总是确定性的吗?

[英]Are C++ std::hash implementations always deterministic?

I know that std::hash<T> are implementation dependent, but are they supposed to be deterministic? 我知道std::hash<T>是依赖于实现的,但它们应该是确定性的吗?

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. 我知道如果我在同一个进程中多次运行std::hash<T>函数,我会得到相同的输出。 However, if I restarted the process, would I get the same value? 但是,如果我重新启动该过程,我会获得相同的值吗? Is there a seed that is used for std::hash? 是否有用于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? 是否保证使用输入X我将始终获得输出Y无论过程运行何时启动,机器还是编译器版本?

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. 这允许盐渍哈希防止碰撞DoS攻击。

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. 这是从C ++ 14开始,但是我们不能假设它可以在C ++ 11中运行,因为没有明确提供这样的保证。

Enabled specializations of std::hash satisfy the Hash requirements ([hash.requirements]), according to which 启用std::hash符合Hash要求([hash.requirements]),根据该要求

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. 无法保证哈希值在调用之间是稳定的,即使这些调用在同一台机器上具有相同的二进制映像。

According to the c++ standard , 根据c ++标准

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. 这允许盐渍哈希防止碰撞DoS攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM