thread_local静态成员模板定义:初始化失败,GCC

thread_local static member template definition: initialisation fails with gcc

本文关键字:初始化 失败 GCC 定义 local 静态成员 thread      更新时间:2023-10-16

当C++类中的静态成员既是thread_local又是成员模板时,它不会被初始化。

#include <unordered_map>
#include <iostream>
class A {
public:
template<typename T>
thread_local static std::unordered_map<int,T> m;
};
template<typename T>
thread_local std::unordered_map<int,T> A::m{};
int main() {
// A::m<int> = std::unordered_map<int,int>{}; // solves the problem
std::cout << A::m<int>.bucket_count() << std::endl; // returns zero.
A::m<int>.insert({1,2}); // causes SIGPFE (hash modulo bucket_count)
}

unordered_map未初始化,存储桶计数为零。这会导致哈希值取模数时除零。没有thread_local或没有template它工作正常。在每个使用它的线程中手动初始化成员(注释行(可以解决问题。

根据C++标准,这是未定义的行为,还是可能是编译器错误?我尝试使用 gcc 7.1.1 和 5.2.0,它们都会产生错误。叮当 3.8 似乎有效。

编辑:我用SVN的gcc 8.0.0 20170817确认了这种行为,并提交了错误报告:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81880

再次,要结束问题:我提交了错误报告,请参阅 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81880