Reputation: 644
I am aware that this question has been asked and answered in different forms over the years, but I find the previous Q&As about it too tied to specific examples and not providing me with a full understanding of why, and in what scenarios, dlls can produce multiple instances of the same singleton. I am struggling to come up with a minimal reproducible example myself.
Given a singleton in the rough form:
class Singleton
{
private:
static Singleton* singleton;
public:
Singelton(); //
~Singleton(); // Not shown for brevity.
static Singelton* getSingleton();
};
Singleton* Singleton::getSingleton()
{
if (!singleton)
{
singleton= new Singleton;
}
return singleton;
}
This is compiled in to a dll (I'll call is SingletonAndOtherStuff.dll
) which is intended for loading via LoadLibrary
by other apps.
This next bit is where I start to get confused.
Within a separate primary app (I'll call it app.exe
), SingletonAndOtherStuff.dll
is loaded via LoadLibrary
in two places. What situations could cause multiple copies of the static variable m_instance
to appear?
app.exe
/ \
static/shared_lib static/shared_lib
\ /
SingletonAndOtherStuff.dll
app.exe
/ \
/ \
static/shared_lib static/shared_lib
| |
SingletonAndOtherStuff.dll SingletonAndOtherStuff.dll
STATIC
and SHARED
libraries between app.exe
and SingletonAndOtherStuff.dll
, could that cause multiple instances of the singleton?I am just looking for an explanation for what would cause this pattern to fall over in the situation where the dll is loaded twice.
Upvotes: 0
Views: 369