为什么thread_local变量在这里从未初始化?
Why is thread_local variable never initialised here?
我正在通过速成课程C++遇到以下代码清单:
#include <cstdio>
struct Tracer {
Tracer(const char* name)
: name{ name } {
printf("%s constructed.n", name);
}
~Tracer() {
printf("%s destructed.n", name);
}
private:
const char* const name;
};
static Tracer t1{ "Static variable" };
thread_local Tracer t2{ "Thread-local variable" };
int main() {
printf("An");
Tracer t3{ "Automatic variable" };
printf("Bn");
const auto* t4 = new Tracer{ "Dynamic variable" };
printf("Cn");
}
这本书的作者声称我应该看到:
Static variable constructed.
Thread-local variable constructed.
A
Automatic variable constructed.
B
Dynamic variable constructed.
C
Automatic variable destructed.
Thread-local variable destructed.
Static variable destructed.
这对我来说非常有意义。但是,当我在我的机器(MacOS,CLion,g ++(上运行它时,我看到以下内容:
Static variable constructed.
A
Automatic variable constructed.
B
Dynamic variable constructed.
C
Automatic variable destructed.
Static variable destructed.
为什么行为不同,t2
变量会发生什么变化?
thread_local
变量可以在线程启动时初始化,但也只能在使用时初始化(标准要求在首次使用之前对其进行初始化(。保证也是,如果初始化,它将在线程终止时被销毁。
相关文章:
- 以下初始化在C++中是否等效
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 缓冲区已使用,但可能尚未初始化(在 Visual Studio 中)
- 容器初始化在 C++98 中
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 程序告诉我初始化在编写简单的C ++代码时不需要初始化的变量
- 没有临时数组的列表初始化 - 在 GCC 中不起作用
- 向量初始化在 C++ 类中失败
- 初始化在三元运算符中捕获 lambda
- 为什么 const char 数组成员的初始化在构造函数初始值设定项中不兼容
- 如何在另一个函数中初始化在 main 中声明的数组
- 初始化在 C++ 中自定义类的构造函数中没有参数的静态 const 类成员
- 初始化在这里很重要
- 函数包装器初始化在 C++11 中是如何工作的
- 正在重新初始化在堆栈上分配的变量
- C++:初始化在初始化列表中创建的对象的引用成员
- 初始化在类的私有成员中声明的静态容器数据
- std::map 迭代器初始化在C++中为零
- 对象数组初始化在C++
- C++ 空队列初始化在 Qt 创建器中不为空