Let's imagine that I have following architecture:
Dodo
singleton class in libdodo
libdodo
and libponny
; Main Program called Dodo::instance()
Ponny
class from libponny
created. It has headers for Dodo
singletonmainwindow.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 libdodo
there is Dodo.cpp
, where you have:
static Dodo& Dodo::instance()
{
static Dodo dodo;
return dodo;
}
Note that local static variables are initialized the first time execution reaches their declaration, so in this case when Dodo::instance
is 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:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
which means that lazy initialization like this becomes kinda bulletproof ;)
A singleton instance is a global. Globals can be shared across DLL/Shared object boundaries, if that is really what you are asking.
You also need to understand the One Definition Rule, which guarantees that indeed there is only one definition of this class, and therefore any static members within the class have just one instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With