Finding C++ static initialization order problems

后端 未结 12 921
情话喂你
情话喂你 2020-11-22 10:10

We\'ve run into some problems with the static initialization order fiasco, and I\'m looking for ways to comb through a whole lot of code to find possible occurrences. Any s

12条回答
  •  滥情空心
    2020-11-22 10:12

    The first thing you need to do is make a list of all static objects that have non-trivial constructors.

    Given that, you either need to plug through them one at a time, or simply replace them all with singleton-pattern objects.

    The singleton pattern comes in for a lot of criticism, but the lazy "as-required" construction is a fairly easy way to fix the majority of the problems now and in the future.

    old...

    MyObject myObject
    

    new...

    MyObject &myObject()
    {
      static MyObject myActualObject;
      return myActualObject;
    }
    

    Of course, if your application is multi-threaded, this can cause you more problems than you had in the first place...

提交回复
热议问题