When is a function registered with atexit() called

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 21:20:15

问题


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?


回答1:


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 to std::atexit is sequenced before the call to the destructor for the object. If a call to std::atexit is 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 to std::atexit. If a call to std::atexit is sequenced before another call to std::atexit, the call to the function passed to the second std::atexit call is sequenced before the call to the function passed to the first std::atexit call.

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.



来源:https://stackoverflow.com/questions/13586451/when-is-a-function-registered-with-atexit-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!