简体   繁体   中英

Using std::hash<uint64_t> for custom class

Do the following two return statements return the same thing?

class NonTrivialClass
{
     public:
        size_t hash() const
        {
            // variation 1
            return std::hash<uint64_t>::_Do_hash(my_val_);

            // variation 2, wanted to avoid creating the named object
            std::hash<uint64_t> hasher;
            return hasher(my_val_);
        }
     private:
        // relevant info for hashing purposes is stored here
        uint64_t my_val_;
}

I intuitively wanted to write something like

return std::hash<uint_64>(my_val_);

which did not compile (because I didn't init an instance of the struct?!). Is there a another way I am missing? Is worrying about creating the named hasher struct unneccessary?

A simpler way of writing it is using a temporary object:

return std::hash<uint64_t>{}(my_val_);

It does the same thing as your second approach.

I can't tell for sure what _Do_hash does, but in any case it is non-standard and should not be used, to avoid portability issues.

Since a google search didn't turn up any documentation of the function, I would assume that it is an implementation detail of the standard library implementation that you are using and that isn't meant to be used by user code. Therefore you shouldn't use it at all, even if you don't care about portability.

Also note that it doesn't matter for performance whether you use your approach with a named variable or my approach using a temporary. The compiler will almost surely generate identical code from it. Which you use is purely a matter of code style.

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