xmllmx
xmllmx

Reputation: 42307

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();
}

Does the C++ standard guarantee g_a will be destructed after tl_a be destructed?

Upvotes: 1

Views: 384

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

Yes it does.

Section [basic.start.term] in the language spec says

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.

So the thread local variables will be destroyed before the static (global) ones.

Upvotes: 3

Related Questions