Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 215
Deqing Avatar asked Jan 16 '14 09:01

Deqing


1 Answers

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.

like image 175
Matthieu M. Avatar answered Nov 07 '22 08:11

Matthieu M.