您的位置:首页 > 运维架构 > Linux

linux下实现单例模式

2016-06-22 09:26 555 查看
Singleton.h

#include <pthread.h>

class Singleton
{
public:
static Singleton* getInstance();
~Singleton();
protected:
private:
Singleton();
static Singleton* instance;
//静态函数中不能有非静态成员变量
//lock要用在静态函数getInstance中进行加锁,因此也必须为static
static pthread_mutex_t lock;
};


Singleton.cpp

#include "Singleton.h"

//c++中的静态变量必须要显式的进行初始化
Singleton* Singleton::instance = NULL;
pthread_mutex_t Singleton::lock = PTHREAD_MUTEX_INITIALIZER;

Singleton::Singleton() {}

Singleton* Singleton::getInstance() {
pthread_mutex_lock(&lock);
if(instance == NULL) {
instance = new Singleton();
}
pthread_mutex_unlock(&lock);
return instance;
}

Singleton::~Singleton() {
//当delete时,instance指向的内存释放了,但还需要将instance赋值为NULL,否则会指向一个非法的地址
instance = NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单例模式 linux c++