Sorry about the late reply - real life got in the way.
What I meant with my previous reply was this:
Singletons are often used for "manager" classes - like "ResourceManager", "NetworkManager", "DatabaseManager" etc.
The classic singleton pattern goes something like this:
class Singleton {
...
static Singleton *instance() { return /* create instance if needed */ m_instance; }
...
};
class SingletonUser {
...
void doStuff() { Singleton::instance()->getResource("foo").doStuff(); }
...
That's nice and convenient for "SingletonUser", but the Singleton class has a number of problems;
- it is effectively a global variable which means that it has all the issues of regular global variables of coupeling classes too tightly.
- it get into trouble with destruction since that happens after main() ends and then the world might not be in a state it can cope with (I've see this too often to find it funny).
- it may itself use other Singleton classes and they may use it and then we have a lot of "fun" centered on who gets instantiated first etc..
- etc etc - I could write a lot about the problems with global variables (and I have done so; just search the forum) and it all applies to singletons + more. I won't repeat myself here.
What you can do instead is to simply construct your "manager" object (or whatever your singleton is) early in "main()" and then pass references to that object to classes that need to access it.
So you'd do something like this:
class TextureManager { ... };
class TextureManagerUser {
TextureManagerUser(const TextureManager& tm) : m_tm(tm) {};
void doStuff() { m_tm.getResource("foo").doStuff(); }
...
};
int main() {
TextureManager tm;
...
TextureManagerUser tmu(tm);
...
}
The lifetime of the "TextureManager object is nicely controlled by being bounded by "main" and yet, the "TextureManagerUser" can be sure it lives long enough since it has been created before itself. It doesn't need a "global" or "static" function to get hold of it - it got a reference when it was constructed and stored that within itself.
See what I'm getting at?