当 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 都产生错误。 clang 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
关于c++ - thread_local 静态成员模板定义 : initialisation fails with gcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45719784/