I want to know if functions registered with atexit() are called before or after global variables are destroyed. Is this specified by the standard or implementation defined?
- 486,780
- 108
- 951
- 1,012
- 20,260
- 32
- 123
- 211
1 Answers
It is well-defined, and depends on whether the object in question was constructed before or after the function got registered using atexit():
3.6.3 Termination
3. If the completion of the initialization of an object with static storage duration is sequenced before a call to
std::atexit(see<cstdlib>, 18.5), the call to the function passed tostd::atexitis sequenced before the call to the destructor for the object. If a call tostd::atexitis sequenced before the completion of the initialization of an object with static storage duration, the call to the destructor for the object is sequenced before the call to the function passed tostd::atexit. If a call tostd::atexitis sequenced before another call tostd::atexit, the call to the function passed to the secondstd::atexitcall is sequenced before the call to the function passed to the firststd::atexitcall.
My layman's interpretation of the above is that stuff that got constructed before you called atexit(handler) gets destroyed after handler() is called, and vice versa. I am sure there are subtleties, but this seems to be the basic principle.
- 486,780
- 108
- 951
- 1,012
-
4Basically, yes. The wording in the Standard is more complicated because in a multithreaded program, "before" and "after" have tricky definitions and don't always act like you'd expect. – aschepler Nov 27 '12 at 14:42
-
1With a note that `constructed` means *the constructor ended* and that we only consider complete objects, not bases or attributes. – Matthieu M. Nov 27 '12 at 14:44