开发者

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!


Store a global 'Foo' instance in Foo (private: static Foo singleton;) and define it somewhere (preferrably Foo.cpp, which needs to be touched unfortunately). This will initialize the object before main() runs - but order of static initialization is undefined across multiple units.

What keeps you from doing this? :

int main() {

   Foo::init(); 
   bar::init();

   LaunchAllMyThreads();
}


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().


In your case, create a global or global static variable (pointer) that accesses your singleton instance function.

Usually when you code a singleton though you will put a static variable inside the class, not a pointer.


Why not create a FooInit class which goes into your Foo.hpp?

class FooInit {
    Foo* pFoo;
public:
    FooInit() : pFoo(Foo::instance()) {}
    ~FooInit() {
        if(pFoo)
            delete pFoo;
    }
};

The initialise the FooInit in your global scope.

#include <Foo.hpp>

FooInit foo_init;

int main() {
    // threads
    // other stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜