简体   繁体   中英

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

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.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

std::hash<std::string> strHash;
strHash(data1);
strHash(data2);

Is re-using one hash struct going to be threadsafe? 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. 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.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

 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. It's okay to create a single hash object and use that for all of the hashes you need (in a singly threaded environment).

Is re-using one hash struct going to be threadsafe? 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. Or you could just use one hash object per thread as they are required to give the same output for the same input. This gives you a little extra space overhead but now you don't have any synchronization overhead which could be costly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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