Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with static member instance

I've got a Singleton implementation where I am not sure which drawbacks it contains. Could anybody tell me how good this implementation is?

template <class Child>
class Singleton {

public:

    inline static Child& Instance() {   
        return Instance_;
    }

    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;

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

protected:

    Singleton() = default;

private:

    static Child Instance_;

};

template <typename Child> Child Singleton<Child>::Instance_;

I know of a Singleton implementation by Scott Meyers that defines the static Instance_ inside the GetInstance() function.

inline static Child& Instance() {   
    static Child Instance_;
    return Instance_;
}

But isn't there additional overhead involved, because it has to check every time the function is invoked whether Instance_ has already been initialized.

like image 332
Philipp Neufeld Avatar asked Dec 02 '25 13:12

Philipp Neufeld


1 Answers

Your solution is prone to static initialization order fiasco.

A static class member is initialized together with all global static variables; before main(), in an unspecified order. If initialization of one static variable happens to reference another one, you get undefined behavior.

Using a static variable in function, however, gives you the special guarantee: the object will only be created when the function is executed for the first time. This means that you don't have to worry about initialization order (unless you create a cycle, obviously).

Regarding performance, the checking is implemented by compiler, so it's probably tuned extremely well. As always, if you're in doubt - benchmark.

like image 121
rburny Avatar answered Dec 05 '25 04:12

rburny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!