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

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

本文关键字:std id thread hash get this lt gt 使用      更新时间:2023-10-16

我目前正在努力让一个C++应用程序在Windows和Linux中编译,在一些调试过程中,我发现

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

不能在带有 gcc 4.8 的 Linux 上编译(感谢此线程中的评论)。对此的建议修复方法是使用:

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

有谁知道这些是否产生相同的输出?

GCC拒绝代码是正确的。该标准没有为std::thread::id定义杆件hash。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>;
}

因此,使用 std::hash<std::thread::id>()(std::this_thread::get_id()) 肯定是获取线程 ID 哈希的有效(实际上是唯一有效)的方法。

我所知,std::thread::id::hash()不在标准中。 所以它可能是一个扩展或实现细节。 因此,它的行为显然将被实现定义。

std::hash<std::thread::id>()(std::this_thread::get_id())在标准中。

由于您不能在多个系统上有一个线程,也不能在任何可移植代码中调用.hash(),因此剩下的就是某些特定于平台的模块使用 .hash() 的可能性,您的通用代码使用 std::hash 。 您可以依靠理智并假定.hash()是相同的,或者您可以扫描特定于平台的模块。 我会自己去扫地。