Is the order guaranteed in this case or is it UB?
#include <iostream>
#include <cassert>
using namespace std;
struct TraceHelper
{
TraceHelper()
{
cout << "TraceHelper::constructor()" << endl;
}
~TraceHelper()
{
cout << "TraceHelper::destructor()" << endl;
}
};
void trace_fn()
{
static TraceHelper th;
cout << "trace_fn()" << endl;
}
void my_atexit()
{
cout << "my_atexit()" << endl;
}
int main()
{
cout << "Entered main()" << endl;
assert(0 == atexit(my_atexit));
trace_fn();
trace_fn();
cout << "Exiting main()" << endl;
return 0;
}
The output:
Entered main()
TraceHelper::constructor()
trace_fn()
trace_fn()
Exiting main()
TraceHelper::destructor()
my_atexit()
What we are looking here is the interaction between the main function and std::exit:
As far as destruction of static objects are concerned, what is relevant to the question are the following lines:
In the code in the question, the function
my_atexit()is registered usingstd::atexit()before the creation of the static objectthin the functiontrace_fn(). Thus, the call of the destructor ofTraceHelperis happening before callingmy_atexit(). The behavior is as expected.