[英]Why does c++ std::hash create a functor struct and can it be called without creating a struct each time
I'm writing a program that needs to perform a lot of hashes very fast, and in a threadsafe way.我正在编写一个程序,该程序需要非常快速地以线程安全的方式执行大量哈希。 For whatever reason c++'s
std::hash
seems to require constructing a functor every time you want to hash a value无论出于何种原因,c++ 的
std::hash
似乎每次你想要 hash 一个值时都需要构造一个仿函数
std::hash<std::string>{}(data);
I'm quite concerned about the overhead of allocating an entire struct every time I want to hash a value, but I don't understand the actual reason a functor is even necessary in this context.我非常担心每次我想 hash 一个值时分配整个结构的开销,但我不明白在这种情况下甚至需要仿函数的实际原因。
Is it safe / correct to create one hash struct then call its operator()
multiple different times?创建一个 hash 结构然后多次调用其
operator()
是否安全/正确?
std::hash<std::string> strHash;
strHash(data1);
strHash(data2);
Is re-using one hash struct going to be threadsafe?重复使用一个 hash 结构会是线程安全的吗? And if not, how would I make it more threadsafe?
如果没有,我将如何使它更线程安全?
but I don't understand the actual reason a functor is even necessary in this context.
但我不明白在这种情况下甚至需要仿函数的实际原因。
There is a good reasons why std::hash
is a functor and not a function and that is that it can have state. std::hash
是函子而不是 function 有充分的理由,那就是它可以有 state。 The C++ standard allows for salted hashes so that each execution of the same program can create different hashed values for the same original value. C++ 标准允许加盐散列,以便同一程序的每次执行都可以为相同的原始值创建不同的散列值。
Is it safe / correct to create one hash struct then call its operator() multiple different times?
创建一个 hash 结构然后多次调用其 operator() 是否安全/正确?
std::hash<std::string> strHash; strHash(data1); strHash(data2);
Yes, that code is safe.是的,该代码是安全的。 You don't need to construct a
hash
every time you want to hash something.每次你想要 hash 的东西时,你不需要构造一个
hash
。 It's okay to create a single hash object and use that for all of the hashes you need (in a singly threaded environment).可以创建一个 hash object 并将其用于您需要的所有哈希(在单线程环境中)。
Is re-using one hash struct going to be threadsafe?
重复使用一个 hash 结构会是线程安全的吗? And if not, how would I make it more threadsafe?
如果没有,我将如何使它更线程安全?
Depends on the use but most likely not.取决于用途,但很可能不是。
std::hash
has no thread safety guarantees so you need to protect the access to it using a mutex or some other synchronization technique. std::hash
没有线程安全保证,因此您需要使用互斥锁或其他一些同步技术来保护对它的访问。 Or you could just use one hash object per thread as they are required to give the same output for the same input.或者您可以只使用一个 hash object 每个线程,因为它们需要为相同的输入提供相同的 output。 This gives you a little extra space overhead but now you don't have any synchronization overhead which could be costly.
这为您提供了一些额外的空间开销,但现在您没有任何可能代价高昂的同步开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.