I did see on internet some pattern for implementing singleton class as following:
class singleton {
public:
int a;
void print()
{
std::cout << a << std::endl;
}
} singleton;
int main()
{
// singleton b; COMPILATION ERROR
singleton.a = 3;
singleton.print();
return 0;
}
It does compile on GCC but I got the feeling that naming the instance as the name of the class is not really a proper way to code.
- Is there any special rules which forbid such convention (instance name same as the class name)
- Is the source code compiling in other compiler ?
Regarding the two question that you literally ask,
yes, C++ has the notion of names of different kinds co-existing in the same scope, as in C, and
yes, when the appropriate header is included the code compiles fine with MinGW g++ 4.4.1, Visual C++ 10.0, and Comeau Online 4.3.10.1.
When you’re in doubt about whether some code snippet is standard-conforming, as a practical matter just submit it to Comeau Online.
That the code is technically OK does not, however, mean that it’s OK… 🙂
Singleton is used to describe something different than a global variable. What you have is a global variable. Ergo, it’s not a singleton.
Two basic properties of a singleton are
there is globally unique instance, and
that instance is created lazily, on demand.
Usually one wants something similar to a global variable but more controlled. One wants a more controlled instantiation order, and the lazy creation helps with that. And one wants to limit the number of allowed instances, usually to
The latter is so common a reason for using singletons that e.g. Wikipedia’s article on singletons describes a singleton as “restricting the instantiation of a class to one object”. But that’s a simplistic view. Sometimes one needs a specific number of instances, as singletons. And e.g. for Python it’s not uncommon to describe Python’s
FalseandTruevalues as singletons of thebooltype. And sometimes one needs a singleton (or singletons) while still allowing arbitrary instantiation.In C++ one particularly easy way to implement a singleton is known as Meyers’ Singleton. Essentially the singleton instance is then a static variable within the function that provides access to it. This is usually combined with prohibiting general instantiation of the class, e.g. by the constructor or all constructors
private, and the singleton access function astaticmember function.Cheers & hth.,