are C++ static variables always destructed on main thread?

Viewed 1900

Short question:

Are C++11 static (non thread_local) variables always destructed on main thread?

Are they always destroyed on program exit only (considering we do not call manually their destructors)?

UPDATE

For brevity, lets assume that destructors ARE called. (we did not pull the plug, we did not kill -9)

1 Answers

Destructors of the global objects are called by std::exit. That function is called by the C++ run-time when main returns.

It is possible to arrange for std::exit to be called by a thread other than that which entered main. E.g.:

struct A
{
    A() { std::cout << std::this_thread::get_id() << '\n'; }
    ~A() { std::cout << std::this_thread::get_id() << '\n'; }
};

A a;

int main() {
    std::thread([]() { std::exit(0); }).join();
}

Outputs:

140599080433472
140599061243648

Showing that one thread called the constructor and another the destructor.

See std::exit and std::atexit for more details.

Related