#include <cstdlib>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::literals;
struct A
{
int n_ = 0;
A(int n) : n_(n) { cout << "A:" << n_ << endl; }
~A() { cout << "~A:" << n_ << endl; }
};
A a1(1);
int main()
{
std::thread([]()
{
static A a2(2);
thread_local A a3(3);
std::this_thread::sleep_for(24h);
}).detach();
static A a4(4);
thread_local A a5(5);
std::this_thread::sleep_for(1s);
std::exit(0);
}
我的编译器是 clang 5.0
,使用了 -std=c++1z
标准。
输出如下:
A:1 A:2 A:4 A:5 A:3 ~A:5 ~A:2 ~A:4 ~A:1
请注意,没有~A:3
,这意味着对象A a3
未被销毁。
然而,根据cppref:
std::exit
导致正常程序终止。执行几个清理步骤:具有线程局部存储期的对象的析构函数...得到保证被调用。