The singleton pattern

One instance, created on first use — in C++ and Python, including the race that lets two instances slip through and the one-line fix.

What you'll learn
  • Implement a lazily created singleton with a private constructor
  • Explain why the classic nullptr check is unsafe with threads
  • Use a function-local static, and know the Python equivalents

Some things should exist exactly once in a program: a logger, a configuration, a connection pool. The singleton pattern makes “exactly once” a property of the class itself. 01_singleton.cpp does it with three ingredients:

class Singleton {
private:
    static Singleton *instance;     // the one instance, shared by all
    Singleton() {}                  // private: nobody else can construct one
public:
    static Singleton *getInstance();
};

Singleton *Singleton::instance = nullptr;

Singleton *Singleton::getInstance() {
    if (!instance) {
        instance = new Singleton();   // created on first use
    }
    return instance;
}

The constructor is private, so new Singleton() outside the class does not compile — the script keeps that line commented out as ILLEGAL!. The only way to get an object is getInstance(), which creates it on the first call and hands back the same pointer ever after. Running the program prints the same address twice, for example 0x5c63c96ba2b0. (The two values run together, because the output line has no separator before Singleton 2:.)

The singleton/ folder splits the same class into singleton.hpp, singleton.cpp and main.cpp. The static member is defined in the .cpp file — it must be defined in exactly one translation unit, which is why it cannot live in the header.

Two calls to getInstance(). Switch to two threads to see both pass the nullptr check before either assigns, and two objects get built; the static-local version builds exactly one.

The race

With threads, the check and the assignment can interleave. Both threads read instance == nullptr, both construct, and the callers end up holding different objects. This is not hypothetical: with a 1 ms pause inserted between the check and the new to widen the window, three runs out of three constructed two instances and handed the two threads different pointers. Formally it is a data race, and undefined behaviour.

The C++11 fix is shorter than the original:

static Singleton &getInstance() {
    static Singleton instance;   // initialised once, even across threads
    return instance;
}

A function-local static is initialised the first time control passes through it, and the standard requires other threads to wait until that initialisation finishes. Run from two threads, it printed constructed once and both got the same address. It also returns a reference — there is no pointer to delete by mistake — and the object is destroyed properly at program exit, whereas the new-ed original never is. Deleting the copy constructor and copy assignment closes the last loophole, copying the instance.

In Python

01_singleton.py shows two approaches in one class:

class Singleton:
    _instance = None

    @staticmethod
    def get_instance():
        if Singleton._instance is None:
            Singleton._instance = Singleton()
        return Singleton._instance

    def __init__(self):
        if Singleton._instance is not None:
            raise Exception("This class is a singleton!")
        Singleton._instance = self

Python has no private constructors, so __init__ refuses a second construction by raising. Running it prints This class is a singleton! once (the deliberate second Singleton()), then the same object address three times. Two notes:

  • The message There exists no object. So, Creating a new instance! never appears, because main() creates the instance with Singleton() before any accessor runs.
  • The instance() classmethod builds its object with cls.__new__(cls), which skips __init__ entirely. Here that is harmless, but any setup code in __init__ would silently not run.

The idiomatic Python singleton is often simpler still: a module is imported only once, so a module-level object already is one.

Try it yourself. Add std::this_thread::sleep_for(1ms) between the check and the new in getInstance(), call it from two std::threads, and count constructions with a std::atomic<int>. Then switch to the static-local version and repeat. In Python, rewrite the class to override __new__ instead of raising in __init__, so Singleton() always returns the one instance.

View source on GitHub →