linux下实现单例模式
2016-06-22 09:26
555 查看
Singleton.h
Singleton.cpp
#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 socket 初步
- 使用C++实现JNI接口需要注意的事项
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- 关于指针的一些事情