全局对象是否保证在所有线程本地存储对象被销毁后被销毁?
Are global objects guaranteed to be destructed after all thread-local-storage objects are destructed?
#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.
因此线程局部变量将在静态(全局)变量之前被销毁。
#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.
因此线程局部变量将在静态(全局)变量之前被销毁。