Singleton implementation in C++

Function that returns singleton:

static SingletonDatabase& get()
{
    static SingletonDatabase db;
    return db;
}

This is a new way to implement this pattern instead of creating a private field static Singleton* instance, and then a separate function that returns it.

I can't understand how it works at all and what does it mean? A local static field, with a default constructor.

Why is this implementation better than the previous ones?

Author: raviga, 2019-03-15

1 answers

This method is not new, it just wasn't thread-safe before (before C++11). How is this implementation better than the previous ones? The fact that it does not require explicit creation of a mutex for multithreaded use, while it takes only 2 lines. This is the simplest Singleton that performs its task. What else do you need?

As for how it works: a static variable (whether it is local or not) is created once. The local one is created at the moment of the first function call and lives until the end of the operation That is, we can assume that the first line of the function is executed only once when it is first called, and in all other cases, the reference is simply returned.

 5
Author: ixSci, 2019-03-16 08:02:07