Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Self-destructing Singleton Inheritance



  • I've been trying to implement a super class that is a self-destructing template-based singleton.
    The purpose is that I have a singleton that automatically destructs if it is no longer used. I've managed to do that, but now I want to create a super class which you can easily inherit. Here is what I currently have:

    @/******************************
    Singleton super class
    ******************************/

    template<typename T>
    class Singleton : public QObject
    {

    public:

    static T* instance()
    {
    if(mInstance.isNull())
    {
    mInstance = QSharedPointer<T>(new T());
    }
    return mInstance.data();
    }

    protected:

    static QSharedPointer<T> mInstance;

    };

    template<typename T>
    QSharedPointer<T> Singleton<T>::mInstance;

    /******************************
    Singleton sub class
    ******************************/

    class MyClass : public Singleton<MyClass>
    {

    protected:

    friend class Singleton<MyClass>;
    MyClass();

    };@

    This code might seem "funny", but it works and eliminates the need to re-implement the instance function in the subclasses.
    The only problem is that I need this statement:

    @friend class Singleton<MyClass>;@

    since Singleton uses the protected constructor of the sub class.
    Any suggestions on how I can change/improve my code so that I don't need a friend?



  • I dont think you can do away with that.
    I can add a few more things which dont help the cause but makes it more readable
    Your Singleton class need not be a subclass of QObject.
    You final class doesnt have to drive from singleton. User of the class can simply say
    SIngleton<MyClass>::instance() and you will get the same effect.



  • Yes, I don't need to inherit from QObject, this was just to accomodate signals/slots. But it doesn't matter here.

    Yes, Singleton<MyClass>::instance() will also work, but I want to encapsulate that. So a programmer can simply call MyClass::instance(), without even knowing/worrying about a super class (aka Singleton).


Log in to reply