饿汉模式
#include
using namespace std;
//饿汉模式
class Singleton
{
public:
static Singleton* GetInstance();
protected:
Singleton(){
cout<
};
private:
Singleton(const Singleton&){};//禁止拷贝
Singleton& operator=(const Singleton&){};//禁止赋值
static Singleton* m_instance;
};
Singleton* Singleton::GetInstance(){
return m_instance;
}
Singleton* Singleton::m_instance = new Singleton();
int main(){
Singleton* m_instance = Singleton::GetInstance();
Singleton* m_instance2 = Singleton::GetInstance();
return 0;
}
懒汉模式
#include
using namespace std;
//懒汉模式
class Singleton
{
public:
static Singleton* GetInstance();
protected:
Singleton(){
cout<
};
private:
Singleton(const Singleton&){};
Singleton& operator=(const Singleton&){};
static Singleton* m_instance;
static pthread_mutex_t mutex;
};
Singleton* Singleton::GetInstance()
{
if( m_instance == NULL)
{
pthread_mutex_lock(&mutex);
if( m_instance == NULL)
{
Singleton* ptmp = new Singleton();
m_instance = ptmp;
}
pthread_mutex_unlock(&mutex);
}
return m_instance;
}
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton* Singleton::m_instance = NULL;
int main(){
Singleton* m_instance = Singleton::GetInstance();
Singleton* m_instance2 = Singleton::GetInstance();
return 0;
}
标签:std,Singleton,饿汉,GetInstance,模式,单例,懒汉
来源: https://blog.csdn.net/weixin_38014640/article/details/100347926