Singleton: How should it be used

后端 未结 24 1956
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:

So I have read th

24条回答
  •  误落风尘
    2020-11-22 05:25

    Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:

    #include
    #include
    
    using namespace std;
    std::mutex mtx;
    
    class MySingleton{
    private:
        static MySingleton * singletonInstance;
        MySingleton();
        ~MySingleton();
    public:
        static MySingleton* GetInstance();
        MySingleton(const MySingleton&) = delete;
        const MySingleton& operator=(const MySingleton&) = delete;
        MySingleton(MySingleton&& other) noexcept = delete;
        MySingleton& operator=(MySingleton&& other) noexcept = delete;
    };
    
    MySingleton* MySingleton::singletonInstance = nullptr;
    MySingleton::MySingleton(){ };
    MySingleton::~MySingleton(){
        delete singletonInstance;
    };
    
    MySingleton* MySingleton::GetInstance(){
        if (singletonInstance == NULL){
            std::lock_guard lock(mtx);
            if (singletonInstance == NULL)
                singletonInstance = new MySingleton();
        }
        return singletonInstance;
    }
    

    Regarding the situations where we need to use singleton classes can be- If we want to maintain the state of the instance throughout the execution of the program If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on. It will be appreciable if anybody can suggest optimisation in my above code.

提交回复
热议问题