C++ singleton code looks like this:
MyClass& MyClass::getInstance(){
static MyClass instance;
return instance;
}
Looking specifically at static MyClass instance;
Is a new instance
created each time getInstance is called?
EDIT
I understand that static members are one-per-class. But doesn’t static MyClass instance
re-declare (and therefore re-create) the “single” instance instance
each time getInstance()
is called?
Because the MyClass
member variable is declared as static
and you are returning a reference to it, not a copy. Static member variables are not created per-object like normal member variables; rather, there is one instance of the variable accessible from all objects of the class.