Dean
Dean

Reputation: 6958

Using C++ new to workaround a static initialization order fiasco

Some of my code is crashing, I think it might be a static order initialization fiasco, the flow goes like this

class MyStorage {
public:

  static MyStorage& instance()
  {
      static MyStorage instance;
      return instance;
  }
};

class MyService {
public:

  MyService() : storage(MyStorage::instance()) {}

  
  MyStorage& storage;
};

MyService service; // This is a global

int main() {
  ...
}

and I suspect the crash is caused by MyStorage using some default values of classes which also have static initializations.

Whether this is the real crash problem or not (and I will do a proper investigation soon), a colleague suggested that I instead use (simple fix/workaround in case this is the real issue):

static MyStorage& instance()
  {
      static MyStorage* instance = new MyStorage();
      return *instance;
  }

my question is: why would using new be better? Wouldn't this new allocation happen at the same time as the other static MyStorage instance; line? Or does new cause this to somehow happen later after all static objects have been initialized?

Upvotes: -1

Views: 88

Answers (0)

Related Questions