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
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.