mardi 28 mars 2017

Why does `std::exit` not behave as expected?

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

My compiler is clang 5.0 with -std=c++1z.

The output is as follows:

A:1
A:2
A:4
A:5
A:3
~A:5
~A:2
~A:4
~A:1

Note that there is no ~A:3, which means the object A a3 was not destructed.

However, according to cppref:

std::exit causes normal program termination to occur. Several cleanup steps are performed:

The destructors of objects with thread local storage duration ... are guaranteed to be called.

Aucun commentaire:

Enregistrer un commentaire