C++ - Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. In modern C++, implementing singletons requires careful consideration of thread safety, initialization order, and destruction semantics.

1. Meyers' Singleton (Recommended)

First introduced by Scott Meyers, this is the modern idiomatic C++ approach:

class Singleton {
public:
    // Global access point
    static Singleton& getInstance() {
        // Guaranteed to be initialized exactly once and thread-safe since C++11
        static Singleton instance;
        return instance;
    }

    // Delete copy constructor and copy assignment operator
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    // Delete move constructor and move assignment operator
    Singleton(Singleton&&) = delete;
    Singleton& operator=(Singleton&&) = delete;

    void doWork() {
        // Business logic...
    }

private:
    Singleton() = default;
    ~Singleton() = default;
};

Why Meyers' Singleton is Thread-Safe (C++11 "Magic Statics")

According to the C++11 standard (§6.7 [stmt.dcl]):

"If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization."

The compiler automatically emits locking code (usually via futex or fast atomic locks under the hood) around the block-scope static variable initialization.

2. Initialization via std::call_once

For cases where you want explicit control over heap allocation or custom error handling during initialization, use std::call_once with std::once_flag:

#include <mutex>
#include <memory>

class SafeSingleton {
public:
    static SafeSingleton& getInstance() {
        std::call_once(initFlag, &SafeSingleton::init);
        return *instance;
    }

    SafeSingleton(const SafeSingleton&) = delete;
    SafeSingleton& operator=(const SafeSingleton&) = delete;

private:
    SafeSingleton() = default;

    static void init() {
        instance.reset(new SafeSingleton());
    }

    static inline std::unique_ptr<SafeSingleton> instance = nullptr;
    static inline std::once_flag initFlag;
};

3. The "Leaky Singleton" (Preventing Static Destruction Order Fiasco)

In multi-threaded applications, other static objects or background worker threads may attempt to access the singleton during process exit after the singleton's destructor has already run. This leads to undefined behavior and segmentation faults upon program termination.

To avoid the static destruction order fiasco, intentionally leak the singleton instance on the heap:

class LeakySingleton {
public:
    static LeakySingleton& getInstance() {
        // Allocated on the heap; destructor will never be called at exit
        static LeakySingleton* instance = new LeakySingleton();
        return *instance;
    }

    LeakySingleton(const LeakySingleton&) = delete;
    LeakySingleton& operator=(const LeakySingleton&) = delete;

private:
    LeakySingleton() = default;
    ~LeakySingleton() = default;
};

The operating system automatically reclaims the memory upon process termination, making intentional leaks safe and desirable for process-lifetime singletons.

Summary of Patterns

Pattern Thread Safe? Destructor Run? Primary Advantage
Meyers' Singleton Yes (C++11+) Yes Simplest, zero boilerplate, optimal performance
std::call_once Yes Yes (if smart ptr used) Fine-grained initialization control
Leaky Singleton (new) Yes (C++11+) No Prevents crashes during static teardown / exit