我正在尝试编写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;
}
答案 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();
};