0

I am trying to code a Singleton. When I compile it I get many undefined errors, like instance and mutex_ in the getSingleton()

undefined reference to 'Singleton::instance'
undefined reference to 'Singleton::mutex_'

#include<iostream>
#include<string>
#include<mutex>
using namespace std;
class Singleton{
public:
    static Singleton* getSingleton(){
        if(instance == NULL){
            mutex_.lock();
            if(instance == NULL){
                instance = new Singleton();
            }
            mutex_.unlock();
        }
        return instance;
    }
private:
    Singleton(){}
    Singleton& operator =(const Singleton& ){}
    static Singleton *instance;
    static mutex mutex_;
};
int main(){
    Singleton* singleton = Singleton::getSingleton();
    return 0;
}
Dale K
  • 25,246
  • 15
  • 42
  • 71
test
  • 1
  • 2

1 Answers1

0

You should place define this static fields to *.cpp file like there

class Singleton{
public:
    static Singleton* getSingleton(){
        if(instance == NULL){
            mutex_.lock();
            if(instance == NULL){
                instance = new Singleton();
            }
            mutex_.unlock();
        }
        return instance;
    }
private:
    Singleton(){}
    Singleton& operator =(const Singleton& ){}
    static Singleton *instance;
    static mutex mutex_;
};

mutex Singleton::mutex_;
Singleton * Singleton::instance;

You can remove the mutex if you use singleton myers and c++11:

class Singleton {
public:
    static Singleton& Instance() {
        static Singleton S;
        return S;
    }

private:
    Singleton();
    ~Singleton();
};
coder80
  • 11
  • 2
  • I need initialize the variable like this ```Singleton* Singleton::instance = NULL; mutex Singleton::mutex_;``` – test Mar 27 '19 at 01:08