未定义对Singleton :: instance

时间:2019-03-20 01:04:34

标签: c++ singleton

我正在尝试编写Singleton。当我编译它时,会遇到许多未定义的错误,例如instance

中的mutex_getSingleton()
  

对'Singleton :: instance'的未定义引用
  未定义对“ 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;
}

1 个答案:

答案 0 :(得分:0)

您应该在* .cpp文件中将定义此静态字段的位置放置在那里

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;

如果使用单例myers和c ++ 11,则可以删除互斥锁:

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

private:
    Singleton();
    ~Singleton();
};