Let’s imagine that I have following architecture:
Dodosingleton class inlibdodo- Main program has linked
libdodoandlibponny; Main Program calledDodo::instance() Ponnyclass fromlibponnycreated. It has headers forDodosingleton
mainwindow.cpp
#include "shared/dodo/dodo.h"
// ...
Dodo::instance()->setNumber(91);
And then, after this call, Ponny class (ponny.cpp) is created
ponny.cpp
#include "shared/dodo/dodo.h"
// ...
bool is = (Dodo::instance()->number() == 91);
// Will `is` be true?
So, can I do it in this way?
Since definitions of behaviour of your singleton are located within its library, it means that singleton instance will be unique and it will exist within the compilation unit where it was created.
Let’s say that in
libdodothere isDodo.cpp, where you have:Note that local static variables are initialized the first time execution reaches their declaration, so in this case when
Dodo::instanceis called first time, so most likely you won’t have any problems with lazy initialization of singleton like this.The only fact that plays role here is thread safety, since there is a possible race condition when more threads call
Dodo::instance()for the first time. For more information I recommend you to read:this question: Singleton & Multi-threading
this article: C++ scoped static initialization is not thread-safe, on purpose!
and this question could help you as well: Thread safe lazy construction of a singleton in C++
Also note that in C++11 (§6.7.4), initialization of static variables is guaranteed to be threadsafe:
which means that lazy initialization like this becomes kinda bulletproof 😉