mardi 10 mars 2020

Check wheter atomic ptr is not initialized in gcc 4.4.7 (without nullptr)

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 compering 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 compere instance ptr to NULL or use nullptr how do I workaround it and check whether it its initialized or not ?

Aucun commentaire:

Enregistrer un commentaire