gpt4 book ai didi

c++ - 未调用已初始化静态 thread_local 结构的构造函数和析构函数

转载 作者:行者123 更新时间:2023-12-01 18:59:59 34 4
gpt4 key购买 nike

下面的代码应该初始化一个静态线程局部静态结构。

#include <iostream>

struct Tracer {
public:
Tracer(const char *new_name) : name{new_name} {
printf("%s : Constructor()\n", this->name);
}

~Tracer() {
printf("%s : Destructor()\n", this->name);
}

private:
const char *name;
};

// 1. Thread-Local Storage Duration
static thread_local Tracer t_thread_local{"Thread-Local Storage Duration"};

// 2. Static Storage Duration
static Tracer t_static{"Static Storage Duration"};

int main() {
printf("Start Program\n");
}

但是,我没有看到来自静态线程本地结构构造函数/析构函数的预期消息。打印的输出仅显示来自 static 结构的消息。我错过了什么吗?

Static Storage Duration : Constructor()
Start Program
Static Storage Duration : Destructor()

最佳答案

您认为仅声明和定义这些对象就一定会触发预main 构造的假设是不正确的。

[basic.stc.thread/2]: [ Note: A variable with thread storage duration is initialized as specified in [basic.start.static], [basic.start.dynamic], and [stmt.dcl] and, if constructed, is destroyed on thread exit ([basic.start.term]). — end note ]

[basic.start.dynamic/5]: It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized. [..]

实际上 basic.start.dynamic 中有许多类似的规则。

重点是,您的程序不会做太多事情,而且它肯定不会使用 t_thread_local,因此由编译器决定 t_thread_local 是否会使用确实存在,如果存在,何时存在。

关于c++ - 未调用已初始化静态 thread_local 结构的构造函数和析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539536/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com