Inherit singleton

Quick question. Do I need to inherit a single singlet so that the child class is single? I searched, but every singleton that I can find is implemented in a class, not in a general way.

+4
source share
2 answers

Yes, there is a general way. You can implement Singleton using CRTP , for example:

template<typename T>
class Singleton
{
protected:
    Singleton() noexcept = default;

    Singleton(const Singleton&) = delete;

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

    virtual ~Singleton() = default; // to silence base class Singleton<T> has a
    // non-virtual destructor [-Weffc++]

public:
    static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
    {
        // Guaranteed to be destroyed.
        // Instantiated on first use.
        // Thread safe in C++11
        static T instance;

        return instance;
    }
};

then output it to make your child Singleton:

class MySingleton: public Singleton<MySingleton>
{
    // needs to be friend in order to 
    // access the private constructor/destructor
    friend class Singleton<MySingleton>; 
public:
    // Declare all public members here
private:
    MySingleton()
    {
        // Implement the constructor here
    }
    ~MySingleton()
    {
        // Implement the destructor here
    }
};

Live on Coliru

+6
source

getInstance(), , . Singleton. , getInstance virtual , Singleton.

class Singleton {
    public virtual Singleton * getInstance() const
    {
        // instantiate Singleton if necessary
        // return pointer to instance
    }
    ...
};

class MySingleton : public Singleton {
    // overrides Singelton getInstance
    public virtual MySingleton * getInstance() const
    {
        // instantiate MySingleton if necessary
        // return pointer to instance
    }
};

, .

+1

Source: https://habr.com/ru/post/1622138/


All Articles