Why does c++ std::hash create a functor struct and can it be called without creating a struct each time

Viewed 191

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?

1 Answers

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.

Related