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.