Why global or static object can lead to crash when

2019-06-18 23:31发布

问题:

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.