0

I've seen posts about this issue but I'm still trying to figure it out. Is this way alright for implementing a safe singelton? I'm using mutex, static member and return its reference.

#include <mutex>
using namespace std;
mutex mtx;

class MySingleton {
private:
    MySingleton();
public:
    MySingleton& getInstance() {
        mtx.lock();
        static MySingleton instance;
        mtx.unlock();
        return instance;
    }
};
Maor Cohen
  • 936
  • 2
  • 18
  • 33

1 Answers1

2

Is this way alright for implementing a safe singelton?

It's overshoot. Just get rid of the mutex and write:

static MySingleton& getInstance() {
    static MySingleton instance;
    return instance;
}

The thread safe creation of instance is guaranteed when the function is called the 1st time.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190