lundi 10 juillet 2023

Thread Safe Singleton in C11

I am aware that C++11 insure that a static variable inside a block scope is thread safe and is always created once only. Using this mysingelton looks something like below.

class singleton
{
    singleton(){}
    singleton(const singleton& s)=delete;
    singleton& operator=(const singleton& s)=delete;

    singleton(singleton&& s)=delete;
    singleton& operator=( singleton&& s)=delete;
    
    public:
     static singleton* GetInstance();
     static std::shared_ptr<singleton> GetInstanceSP();
          
};

singleton* singleton::GetInstance()
{
        static singleton sObject;
        return &sObject;
}

But this will have an issue, sObject will obviously be destructed before the Object which is using it if the caller is static or global. So I tried below solution which looks and working good

std::shared_ptr<singleton> singleton::GetInstanceSP()
{
        static std::shared_ptr<singleton> sp(new singleton);
        return sp;
}

Is this solution OK? or still it has some loopholes. I didn't go for unique_ptr for same reason as its destructor will be called before its client.

Also one more query: Will below code is also thread safe? if so why this is not in any book or refrence example

static singelton *sp(new singelton);
reurn sp;

W

Aucun commentaire:

Enregistrer un commentaire