singleton and new operator - thread safety

Viewed 65

I know that a Scott Meyers Singleton is thread-safe for C++11 and above. Is the following code also thread-safe (for C++11 and above)?

class T
{
    static T* obj;
public:
    T& GetInstance()
    {
        if (!obj)
        {
            obj = new T();
        }
        return *obj;
    }
};
T* T::obj=nullptr;
2 Answers

No, this code is not thread safe. Two or more different threads could all call GetInstance at the same time and since obj has no synchronization (mutex, atomic variable) guarding it, then you have a data race. Having a data race means your code has undefined behavior which is not safe.

It is not thread-safe:

Two threads calling GetInstance at the same time could both enter the if block and allocate twice.

The returned object could also mismatch.

Related