Template Class Singleton

Nested Relationships

Nested Types

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 A do:

class A : Singleton<A> {
  private:
    friend class Singleton<A>;
    A(...);  // define (private) constructors
};
Here’s how to use it:
// 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
Singleton is thread-safe, in that multiple threads can call A::instance(), even if A::set_instance() has not been called yet.

Public Static Functions

static inline Derived &instance()
Throws:

std::logic_error – 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 returns pointer to the instance, or nullptr if the instance has not been constructed

Returns:

pointer to the instance, or nullptr if it has not yet been constructed

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:

std::logic_error – if the instance has already been constructed

Returns:

reference to the newly-created instance

Protected Functions

template<typename ...Args>
inline Singleton(Args&&... args)

Protected Static Functions

static inline auto &instance_accessor()
static inline auto &instance_mutex()