为什么静态thread_local对象在C++构造两次
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(确切地说是Devuan ASCII(上使用clang++ 8和g++ 8.2,线程局部变量只构造一次。
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 对结构向量进行两次排序
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- 谷歌测试发现在macOSX上添加并运行了我的所有测试两次