gpt4 book ai didi

c++ - 全局对象是否保证在所有线程本地存储对象被销毁后被销毁?

转载 作者:行者123 更新时间:2023-11-30 02:26:15 25 4
gpt4 key购买 nike

#include <thread>

using namespace std;

struct A
{
A() {}
~A() {}
};

A g_a;

int main()
{
thread([]()
{
thread_local A tl_a;
exit(0);
}).detach();
}

C++标准是否保证g_a会在tl_a被析构后被析构?

最佳答案

是的。

语言规范中的 [basic.start.term] 部分说

Destructors (12.4) for initialized objects (that is, objects whose lifetime (3.8) has begun) with static storage duration are called as a result of returning from main and as a result of calling std::exit (18.5). Destructors for initialized objects with thread storage duration within a given thread are called as a result of returning from the initial function of that thread and as a result of that thread calling std::exit. The completions of the destructors for all initialized objects with thread storage duration within that thread are sequenced before the initiation of the destructors of any object with static storage duration.

因此线程局部变量将在静态(全局)变量之前被销毁。

关于c++ - 全局对象是否保证在所有线程本地存储对象被销毁后被销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083856/

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