Possible Duplicate:
What is so bad about singletons?
Singleton pattern in C++
I want to create a singleton class. For that, I created a class with all its member and methods as static. Something like this.
class a
{
static int a;
static GetA();
}
Now all the classes who want to use my singleton class cannot create any object for my class and also will get same value. I just want to know whether this implementation will solve all the purpose and fulfill all criteria for creating a singleton class.
The conventional Singleton (anti-)pattern isn’t a collection of static variables; rather, it is an object with non-static members, of which only one instance can exist.
In C++, this allows you to avoid the biggest problem with static variables: the “initialisation order fiasco”. Because the initialisation order is unspecified for static variables in different translation units, there’s a danger that the constructor of one might try to access another before it is initialised, giving undefined behaviour. However, it introduces other problems (a similar “destruction order fiasco”, and thread safety issues in older compilers), so it’s still something to avoid.
If you want a collection of static variables and functions, then put them in a namespace rather than a class:
If you think you want a singleton, then think again; you’re generally better avoiding globally accessible objects altogether. If you still want one, then you would make a class with a private constructor, and a public accessor that returns a reference to the single instance, along the lines of: