I'm new and a little ignorant in C++ and I encounter a C++ code that used a singleton pattern,
class CFoo
{
public:
static CFoo& getInstance()
{
static CFoo self;
return self;
}
private:
CFoo(){}
~CFoo(){}
};
I am just confused why return a static reference? Is this a valid code? Why the programmer didn't use a pointer?
Why use a pointer? A reference is simple and matches what I want to do: alias an object, not point to it. The static
doesn't apply to the reference, it applies to the function, making it callable without an instance.
(Even better, why use a singleton?)
A static local variable e.g. self
once initialized (one first pass through the function getInstance) remains for the entire duration of the program unless explicitly deleted. Therefore it is perfectly safe to return the reference to self
.
Note that it is getInstance
which is static in the function declaration. Storage class specifiers are not allowed on return types of a function.
I would suggest you to use the Monostate design pattern unless of course the need for Singleton is strongly suggested
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With