mardi 4 juin 2019

How to implement singleton pattern destructor and attributes c++? [duplicate]

This question already has an answer here:

I'm implementing the singleton pattern but I have some concerns with the static attributes and methods. Is a good practice have static attributes and non-static methods?? What about the destructor, can I get a simple delete mInstance??

I already made a little research but I'm still confusing about the best practices for the singleton implementation.

class MySingleton
{
    public:
        enum CustomSizes
        {
            CS_USHORT = 12,
            CS_FLOAT = 20
        };

        static MySingleton* getInstance()
        {
            if(!mInstance)
            {
                mInstance = new MySingleton();
            }
            return mInstance;
        }

        void fillArrayWithValue(float value){ /*...*/ }
        void fillArrayWithValue(unsigned short value){ /*...*/ }

    private:
        MySingleton();

        static MySingleton *mInstance;

        MySingleton(MySingleton const&) = delete;
        void operator=(MySingleton const&) = delete;

        template <typename T>
        void fillArray(T* table){ /*...*/ }

        static unsigned short arrayUshort[CS_USHORT];
        static float arrayFloat[CS_FLOAT];
};

Should I implement a simple destructor for the static instance? Should I convert the static attributes to non-static? Should I convert the non-static methods to static methods?

Aucun commentaire:

Enregistrer un commentaire