跳转至

cf::Singleton

Thread-safe singleton with explicit initialization. More...

#include <singleton.hpp>

Public Functions

Name
template <typename... Args>
T &
init(Args &&... args)
Initializes the singleton with the provided arguments.
T & instance()
Returns the singleton instance.
void reset()
Resets the singleton instance.
Singleton(constSingleton & ) =delete
Singleton & operator=(constSingleton & ) =delete

Protected Functions

Name
Singleton() =default
virtual ~Singleton() =default

Detailed Description

template <typenameT >
class cf::Singleton;

Thread-safe singleton with explicit initialization.

Template Parameters:

  • T Type of the singleton instance.

Note: Thread-safe. Uses std::call_once for initialization.

Warning: Accessing instance() before calling init() throws std::logic_error.

Provides a singleton implementation that requires explicit initialization via init() before accessing the instance. This pattern allows for parameterized construction and explicit control over initialization timing.

class MyClass {
public:
    MyClass(int value) : value_(value) {}
    void doSomething() {}
private:
    int value_;
};

using MySingleton = Singleton<MyClass>;
MySingleton::init(42);
MySingleton::instance().doSomething();

Public Functions Documentation

function init

template <typename... Args>
static inline T & init(
    Args &&... args
)

Initializes the singleton with the provided arguments.

Parameters:

  • args Arguments to forward to T's constructor.

Exceptions:

  • None

Template Parameters:

  • Args Types of constructor arguments.

Return: Reference to the initialized singleton instance.

Since: N/A

Note: Thread-safe initialization guaranteed by std::call_once.

Warning: Calling init() twice has no effect; the first instance is kept.

Constructs the singleton instance once, subsequent calls return the existing instance. Thread-safe via std::call_once.

function instance

static inline T & instance()

Returns the singleton instance.

Exceptions:

  • std::logic_error if init() has not been called.

Return: Reference to the singleton instance.

Since: N/A

Note: None

Warning: Must call init() before accessing instance().

Requires that init() has been called first.

function reset

static inline void reset()

Resets the singleton instance.

Exceptions:

  • None

Since: N/A

Note: After calling reset(), init() must be called again before accessing instance().

Warning: None

Destroys the current instance and allows re-initialization via init().

function Singleton

Singleton(
    constSingleton & 
) =delete

function operator=

Singleton & operator=(
    constSingleton & 
) =delete

Protected Functions Documentation

function Singleton

Singleton() =default

function ~Singleton

virtual ~Singleton() =default

Updated on 2026-03-09 at 10:14:00 +0000