I work in a project where Singletons are usually implemented like this:
class Singleton { public: static Singleton& get(); virtual ~Singleton() = default; // Used for unit tests static void reset(); protected: static std::unique_ptr<Singleton>& instance(); }; unique_ptr<Singleton>& Singleton::instance() { static unique_ptr<Singleton> instance; return instance; } Singleton& Singleton::get() { auto& instance = instance(); if (!instance) { // We cannot use make_unique<T>() as constructor is private instance = unique_ptr<Singleton>(new Singleton()); } return *instance; } void Singleton::reset() { instance().reset(); } // Private constructor Singleton::Singleton() {} No thread safety is required here.
Is there any advantages of using a static unique_ptr ?
What are the consequences of creating the Singleton with unique_ptr<T>(new T()) ?
Since our Singletons can carry (some) global state, a public reset() was implemented for testing purposes, is it the only way and can this be improved ?
I have found some examples of C++ singleton design patterns here. But never implemented with unique_ptr like mine.
std::unique_ptr<Singleton>& instance();instead:Singleton& instance();? Are you planing to allow external code to destroy instance ofSingelton?unique_ptr, why not declare and initialize it inget()and get rid ofinstance()?Singleton& Singleton::get() { static unique_ptr<Singleton> instance(new Singleton()); return *instance; }For that matter, why use aunique_ptrat all? Do you really need toreset()a singleton? The typical (and thread-safe) implementation is to just use astaticobject, eg:Singleton& Singleton::get() { static Singleton instance; return instance; }unique_ptrhere. All this implementation has done is reduce the thread safety.Singleton& Singleton::get() { static Singleton instance; return instance; }is more thread safe and has the same result. Thread safety may not be important now, but it doesn't hurt either.create()andget()is needed (e.g creation with parameters)instance()is just a shortcut. I apologize, it's not very useful in my example.unique_ptrfor a singleton. Use a Meyers' Singleton instead