Template Class Singleton¶
Defined in File singleton.hpp
Class Documentation¶
-
template<typename Derived>
class Singleton¶ Singleton base class Singleton is a CRTP base class that provides a thread-safe way to create an immutable singleton object.
To create a singleton class
Ado:Here’s how to use it:class A : Singleton<A> { private: friend class Singleton<A>; A(...); // define (private) constructors };
Singleton is thread-safe, in that multiple threads can call// optional: create the instance of A A::set_instance(Args...); // this call-once method creates the instance of A; if A is default-constructible, can skip this as the instance will be created by first call to instance() // access the instance of A A& the_instance = A::instance(); // throws if A is not default-constructible or A::set_instance() had not been called to create the instance // ... or ... A* the_instance_ptr = A::instance_ptr(); // alternative to A::instance(), instead of throwing, returns nullptr // the instance of A will be destroyed with other static-linkage objects
A::instance(), even ifA::set_instance()has not been called yet. The instance must not be used after it has been destroyed, i.e. do not callA::instance()from the destructor of a static-linkage object that was constructed before the instance of A.Public Static Functions
-
static inline Derived &instance()¶
- Throws:
Exception – if the instance has not been constructed (because Derived is not default-constructible and set_instance() had not been called)
- Returns:
reference to the instance
-
static inline Derived *instance_ptr()¶
same as instance(), but instead of throwing returns nullptr if the instance has not been constructed; like instance(), constructs the instance on first use if Derived is default-constructible
- Returns:
pointer to the instance, or nullptr if Derived is not default-constructible and set_instance() has not been called
-
template<typename ...Args>
static inline Derived &set_instance(Args&&... args)¶ Constructs the instance. This must be called if Derived is not default-constructible.
- Template Parameters:
Args – a parameter pack type
- Parameters:
args – a parameter pack
- Throws:
Exception – if the instance has already been constructed
- Returns:
reference to the newly-created instance
Protected Static Functions
-
static inline auto &instance_mutex()¶
provides mutex that serializes construction of the instance
-
static inline Derived &instance()¶