tags:

views:

89

answers:

4

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: 

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.

Brian R. Bondy
"static variable inside the class, not a pointer"Would that work in situations where the Singleton is initialized based on a runtime input?
CodeMedic
If you needed some runtime input to create the type itself then you could use new.
Brian R. Bondy
+1  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().

Potatoswatter
Interdependences: yes.
anon
+2  A: 

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();
}
Alexander Gessler
A: 

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
}
CodeMedic