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
staticdoesn’t apply to the reference, it applies to the function, making it callable without an instance.(Even better, why use a singleton?)