Q:

Force initialization of singleton in c++ before main()

I am using singletons as follows:
// Foo.hpp
class Foo {
  static Foo* instance() {
    static Foo* foo = new Foo();
    return foo;
  }
}

Now, my singleton is initialized the first time Foo::instance() is called. I want to make sure this is before main executes (my code is multi threaded, I want all singletons initialized before pThreads are created).
Question is:
Is there anything I can put in Foo.hpp to make the above happen? (I don't want a generic Globals.hpp taht initializes all singletons; I'd also prefer to not have to touch Foo.cpp).
Thanks!

A:

Your usage of singletons indicates interdependencies between them. Is that the case? Also, you shouldn't allocate it on the heap; it will never be be destroyed.
class Foo {
  static Foo& instance() {
    static Foo foo; // no pointer needed
    return foo;
  }
};

Anyway, the answer you ask for is to add such a dependency:
class InitStons {
  InitStons() {
    Foo::instance();
  }
} master_initialize;

But this is really not good practice, and you should just initialize things at the beginning of main().

