Detecting if I am in an exit handler in C++

Viewed 87

I would like to know if I am in an atexit() handler. I'm looking for the moral equivalent of std::uncaught_exceptions() for exit() calls.

I want to do this so I can have the destructors in my static objects behave one way when my main() function returns, and another way when exit() is called.

I could add a call to atexit() that sets a bool I inspect, but that runs into ordering issues. For example, this:

#include <iostream>
#include <stdlib.h>

struct Setter {
    static void set_in_at_exit() { in_at_exit = true; std::cout << "setting\n";}
    Setter() { std::cout << "constructor\n"; atexit(set_in_at_exit); }
    static bool in_at_exit;
};

bool Setter::in_at_exit = false;

struct A {
    A() { static Setter s; }
    ~A() { if (Setter::in_at_exit) {
            std::cout << "in at exit\n";
        }
    std::cout << "My destructor\n"; }
};

A a;

int main()
{
    return 0;
}

produces:

constructor
My destructor
setting

Which is not what I want. The destructor doesn't know it is in an exit handler.

1 Answers

[basic.start.main]
A return statement (8.6.3) in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control flows off the end of the compound-statement of main, the effect is equivalent to a return with operand 0

So no, you cannot distinguish between the two situations unless you somehow instrument all explicit calls to exit or all return statements and the last line before the closing brace in main.

Related