samedi 12 mars 2016

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.

Thanks in advance, Philinator

Aucun commentaire:

Enregistrer un commentaire