Why does C++ Core Guidelines prefer simplest “singleton” as a function but not as a static member function?

114 Views Asked by At

C++ Core Guidelines, I.3: Avoid singletons:

Exception You can use the simplest “singleton” (so simple that it is often not considered a singleton) to get initialization on first use, if any:

X& myX()
{
    static X my_x {3};
    return my_x;
}

Enforcement

  • If a class X has a public static function that contains a function-local static of the class’ type X and returns a pointer or reference to it, ban that.

Why do they ban that?

class X {
 public:
  static X& Get() {
    static X my_x {3};
    return my_x;
  }
};

X::Get() is not worse than myX(). X::Get() is even better than myX() with the stupid prefix "my".

1

There are 1 best solutions below

0
JaMiT On

The enforcement operates on probability and heuristics.

What does it mean for a singleton to be "simplest" and thereby qualify for the exception? The guidelines are vague on this point (a real example would help), but the characterization "often not considered a singleton" suggests that the the singleton's class does not require it to be used as a singleton. So a class that tries to be a singleton does not qualify as "simplest".

This section of the guidelines gives an example of a class that tries to be a singleton, noting that, inside the class definition, there is often

lots of stuff to ensure that only one Singleton object is created

A static member function meeting the given criteria is commonly part of this "lots of stuff". The existence of such a function is a sign that the class was designed to be used as a singleton, so this class does not qualify for the exception. This is not 100% conclusive, but it holds often enough for the guideline's purposes (apparently). Banning this helps achieve compliance with the guidelines.

In contrast, if a class is not designed as a singleton then it is relatively easy to create a non-member function implementing a singleton pattern. So such a non-member function is allowed (even though there is no guarantee that it qualifies for the exception). Again, this is not 100% conclusive, which is why enforcement is called "Very hard in general."

Could there be a better plan for enforcement? Possibly.