Why global or static object can lead to crash when program exit?

大憨熊 提交于 2019-12-23 08:08:06

问题


In C++ Singleton design pattern, obecalp mentioned that:

For many larger programs, especially those with dynamic libraries. Any global or static object that's none primitive can lead to segfaults/crashes upon program exit on many platforms due to order of destruction issues upon libraries unloading. This is one of the reasons many coding conventions (including Google's) ban the use of non-trivial static and global objects.

Can someone elaborate why this can happen? Maybe an example to explain it?


回答1:


You may have heard of the static initialization order fiasco where a global being built references another global that is not yet built. The general solution to this issue is to use lazy initialized objects (initialization on first use).

Well, the same fiasco may occur at destruction time, if the destructor of an object references another object which is already destructed; and unfortunately there is no silver bullet solution to this issue since the code of a destructor can be arbitrarily complex.

One solution is simply to forbid the use of this ill-mannered feature.




回答2:


I am posting this as an answer, because I do not understand why this is not used:

Simply make one single global object on stack (from a class) and allocate every global you want into that one (member pointer, allocated on heap). You can have accessors for those global objects and then destroy them in the destructor of the global object, with perfect control over the order of construction/deconstruction of each.

Oh, and by the way, you can have locks in there too, including between the "global" objects.



来源:https://stackoverflow.com/questions/21157476/why-global-or-static-object-can-lead-to-crash-when-program-exit

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