2 ms·
The singleton thing is interesting, I admit I overlooked the scope thing. In practice though, I only ever used it to overcome a particular C++ deficiency: init
by loup-vaillant 9y ago
The singleton thing is interesting, I admit I overlooked the scope thing. In practice though, I only ever used it to overcome a particular C++ deficiency: initialisation dependencies. C++ doesn't specify the order of initialisation across compilation units, so I can't just lean on constructors.
To ensure initialisation occurs only once, a static scope and a constructor are enough. And to ensure nobody else can spin up another instance, the constructor can be private, though I've never needed that. Anyway, for extra "clean" points, I tend to just expose the interface of the singleton as a set of global functions, doing whatever's necessary for the user to not having to think about initialisation or `get_instance()` at all.
If C++ could guaranteed the order of initialisation satisfies dependencies, we could shave a few lines off that pattern. (Whether this is a good idea is a separate issue.) My point was, each pattern has a corresponding language feature (or set thereof) that could make it less verbose.