[英]Why is a static thread_local object in C++ constructed twice?
这段代码:
#include <iostream>
#include <thread>
#include <mutex>
struct Singl{
Singl(Singl const&) = delete;
Singl(Singl&&) = delete;
inline static thread_local bool alive = true;
Singl(){
std::cout << "Singl() " << std::this_thread::get_id() << std::endl;
}
~Singl(){
std::cout << "~Singl() " << std::this_thread::get_id() << std::endl;
alive = false;
}
};
static auto& singl(){
static thread_local Singl i;
return i;
}
struct URef{
~URef(){
const bool alive = singl().alive;
std::cout << alive << std::endl;
}
};
int main() {
std::thread([](){
singl();
static thread_local URef u;
}).join();
return 0;
}
具有以下输出:
Singl() 2
Singl() 2
1
~Singl() 2
~Singl() 2
我正在使用mingw-w64 gcc7.2 POSIX线程在Windows下编译和运行。
Coliru具有不同的输出: http ://coliru.stacked-crooked.com/a/3da415345ea6c2ee
这是什么? 我的工具链/编译器出问题了,还是应该这样? 为什么在同一线程上有两个thread_local对象(或构造两次?)?
您的编译器或工具链可能有问题。
在Linux上使用clang ++ 8和g ++ 8.2(确切地说是Devuan ASCII)时,线程局部变量仅构造一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.