During re-factorization of singleton class to be thread safe (fallowing Herb Sutter advice how to write proper double-check locking) I came across problem with my version of compiler (gcc 4.4.7 with --std=c++0x flag) supporting atomics but not supporting nullptr.
Current code
class SingletonClass {
public:
SingletonClass* getInstance() {
if (instance == NULL) {
instance == new SingletonClass();
}
return instance;
}
private:
SingletonClass() = default;
~SingletonClass() = default;
static SingletonClass* instance;};
What I would like to achive
#include <cstdatomic>
#include <mutex>
class SingletonClass {
public:
SingletonClass* getInstance() {
if (instance == NULL) {
std::lock_guard<std::mutex> lock (m);
if(instance == NULL){
instance = new SingletonClass();
}
}
return instance;
}
private:
SingletonClass() = default;
~SingletonClass() = default;
static std::atomic<SingletonClass*> instance;
static std::mutex m;
};
But this gives me error saying that there is no operator for comparing atomic ptr to NULL
main.cpp: In member function ‘SingletonClass* SingletonClass::getInstance()’:
main.cpp:7: error: ambiguous overload for ‘operator==’ in ‘SingletonClass::instance == 0l’
main.cpp:7: note: candidates are: operator==(void*, void*) <built-in>
main.cpp:7: note: operator==(SingletonClass*, SingletonClass*) <built-in>
Since I can't either compare instance ptr to NULL or use nullptr how do I work around it and check whether it is initialized or not ?
Edit: I think Yksisarvinen's answer above is better. You already have the lock, don't bother anymore. Leaving my old answer below.
I'm not sure about the specific GCC version, but if
<atomic>is there theoretically this should work:As per the documentation,
load()should give you what you want, the pointer itself to compare to, which should work with NULL.Good luck on old compilers. I've had to do that too on occasion due to customer requirements.