为什么thread_local变量在这里从未初始化?

Why is thread_local variable never initialised here?

本文关键字:初始化 在这里 变量 thread local 为什么      更新时间:2023-10-16

我正在通过速成课程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

变量可以在线程启动时初始化,但也只能在使用时初始化(标准要求在首次使用之前对其进行初始化(。保证也是,如果初始化,它将在线程终止时被销毁。