Be-careful when using the atexit() routine with "static" objects
BasilTK 060001VVJ7 Visits (7933)
Recently, while helping a client debug their application, we ran into a scenario where atexit() was being used with "static" objects. Interestingly enough, the position of the atexit() routine was affecting the order of the destructor calls for their static objects. Some applications may depend on a specific order of destructor calls. So if atexit() is not used properly, it can cause unexpected runtime behavior.
Let's consider the following example:
For CASE1, you will see the following output at runtime:
and for CASE2, you will see the following output at runtime:
As a user, one might always expect the cleanup function call to occur first ie, where the function registered with atexit() is processed before the static object is destroyed. However, this is not the case.
According to the C++ Standard, for an object with static storage duration constructed after a function is registered with atexit(), then following the call to exit, the registered function is not called until the execution of the object’s destructor has completed (ie CASE1).
If a function is registered with atexit() then following the call to exit, any objects with static storage duration initialized prior to the registration of that function shall not be destroyed until the registered function is called from the termination process and has completed (ie CASE2).
So, next time when using the atexit() function, be sure to keep this in mind to avoid potential runtime problems!
Feel free to post comments if further discussion is required.