Using std :: hash <std :: thread :: id> () (std :: this_thread :: get_id ())

I am currently working on building a C ++ application on Windows and Linux, during some debugging I found that

std::this_thread::get_id().hash()

      

does not compile on Linux with gcc 4.8 (thanks to the comments in this thread ). The suggested fix for this was to use:

std::hash<std::thread::id>()(std::this_thread::get_id())

      

Does anyone know if they produce the same result?

+3


source to share


2 answers


GCC reserves the right to reject the code. The standard does not define a member hash

for std::thread::id

. C ++ 11, 30.3.1.1:

namespace std {
  class thread::id {
  public:
    id() noexcept;
  };

  bool operator==(thread::id x, thread::id y) noexcept;
  bool operator!=(thread::id x, thread::id y) noexcept;
  bool operator<(thread::id x, thread::id y) noexcept;
  bool operator<=(thread::id x, thread::id y) noexcept;
  bool operator>(thread::id x, thread::id y) noexcept;
  bool operator>=(thread::id x, thread::id y) noexcept;

  template<class charT, class traits>
    basic_ostream<charT, traits>&
      operator<< (basic_ostream<charT, traits>& out, thread::id id);

  // Hash support
  template <class T> struct hash;
  template <> struct hash<thread::id>;
}

      



So using std::hash<std::thread::id>()(std::this_thread::get_id())

is definitely a valid (actually the only valid) way to get a stream ID hash.

+5


source


std::thread::id::hash()

not up to standard as far as I can tell. So this is probably an extension or implementation of a part. Thus, his behavior will obviously be implemented.

std::hash<std::thread::id>()(std::this_thread::get_id())

is in the standard.



Since you cannot have a thread on multiple systems, and you cannot call .hash()

in any portable code, what remains is that some platform-specific modules use .hash()

your common code using std::hash

. You can rely on your sanity and believe that .hash()

is the same, or you can sweep your platform module. I would go in a big way.

0


source







All Articles