I have a class T
and want a single global object of that class given by accessor functions like T const& read_singleton()
and T& modify_singleton()
. The object should be instantiated at first use of one of these functions by the default constructor of T
and the usage of the functions should be thread-safe. What is a (good) design pattern to achieve this?
It's easy enough to write these functions:
T& modify_singleton()
{
T static t{};
return t;
}
T const& read_singleton()
{
return modify_singleton();
}
This is the Meyers singleton pattern and can also be implemented as static functions of T
, in case you have control over its implementation and want to make its constructor/destructor and such private.
The initialisation of variable t
will be thread-safe. However, what happens when multiple threads obtain a T&
is outside the control of modify_singleton
. You will have to coordinate modifications to the object, either with a global mutex or by designing its class to be thread-safe. If you cannot modify class T
, you could also provide a thread-safe interface through a wrapper class.