First your code in main
won't compile. Object
default constructor is private, so you won't be able to do :
Object* object = new Object();
Second, as instance()
is static (means not related to any instance) there is no need to call it from an object, the class name suffices :
Object& theInstance = Object::instance();
Finally, the code of instance is :
static Object& instance()
{
static Object z;
return z;
}
It's OK. A static
variable in a C++ function means that the object is instanciated once : when the function is ran for the first time. Then z
won't be destroyed at the end of the function (contrary to other so-called local variables) and will be re-used for next calls of instance
.
So at first call of instance
:
z
is createdz
z is returned
At next calls :
z
is returned
A singleton is a class which implies only one instance will be created. You can verify the objects are the same with :
Object& a = Object::instance();
Object& b = Object::instance();
std::cout << &a << std::endl;
std::cout << &b << std::endl;
a
and b
should have the same memory adress.
This is the expected behaviour of a singleton : if the object construction function (instance
) is called several times, the same instance will be returned.
So as you said, instance
actually prevents the creation of two Object
. Maybe you expected you program to return some error on the second call of instance
. If you wan't this behaviour, you'll have to make it yourself using expections or returning NULL
. Yet, The code you wrote shows the classic way singletons are done in C++.