Daily bit(e) of C++ | Singleton pattern
Daily bit(e) of C++ #138, The simplest singleton pattern, a.k.a. Scott Meyer's singleton.
Singletons should be avoided if possible, as they introduce a hurdle for testing. However, sometimes a global state might be the least bad choice.
If you need a Singleton, use a simple getter function that returns a reference to a local static variable.
Block-scope static variables are initialized in a thread-safe and exception-safe manner.
I used to like that and it is a great way to have a thread safe singleton but it is horrible when doing unit testing. Nowadays I use a unique_ptr protected with a mutex, sure a bit more overhead but at least I can fully destroy the singleton between unit tests. Just my 2c.