使用 std::hash<std::thread::id>()(std::this_thread::get_id())
Using std::hash<std::thread::id>()(std::this_thread::get_id())
我目前正在努力让一个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()
是相同的,或者您可以扫描特定于平台的模块。 我会自己去扫地。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 在运行之前获取 std::thread's thread:id?
- std::map和id不断递增
- 错误:数字常数之前的预期无限制ID:std :: array和std ::向量大小分配
- 从 std::thread::id 结构中检索 Windows 线程标识符
- std::thread::id 是否有"null"值?
- std::this_thread::get_id() vs passing ID
- 如何在 c++ 中将 std::thread::id 转换为字符串
- 使用 std::hash<std::thread::id>()(std::this_thread::get_id())
- 我不断收到来自Xcode的错误,说" Apple Mach-O Linker (Id) Error "readIt(std::_1::basic_ifstream<char,std::_1::c
- 在std::unordered_map中分配ID后创建对象
- 如何从std::ofstream获取文件id
- std::thread::id 默认构造函数不应该创建一个"NULL" id吗?
- std::thread::id 中的分段错误::运算符==
- 在映射中使用std::thread::id可以确保线程安全
- c++:std::map数字id的迭代排序-交叉编译器