Chinaunix首页 | 论坛 | 博客
  • 博客访问: 321715
  • 博文数量: 49
  • 博客积分: 653
  • 博客等级: 上士
  • 技术积分: 646
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-01 22:43
文章分类

全部博文(49)

文章存档

2018年(1)

2017年(4)

2015年(1)

2014年(6)

2013年(8)

2012年(24)

2011年(5)

分类: C/C++

2017-05-18 20:11:39


单例在资源管理相关等方面 基本上是必须使用的。


代码:


点击(此处)折叠或打开

  1. #include<iostream>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. using namespace std;
  5. class noncopyable {
  6. protected:
  7.     noncopyable(){};
  8.     ~noncopyable(){};
  9. private:
  10.     noncopyable(const noncopyable&);
  11.     const noncopyable& operator=(const noncopyable&);
  12. };

  13. template <typename T>
  14. class Singleton : public noncopyable {
  15. public:
  16.     static T* instance() {
  17.         pthread_once(&ponce_, &Singleton::Init);
  18.         return value_;
  19.     }

  20. private:
  21.     Singleton();
  22.     ~Singleton();

  23.     static void Init() {
  24.         value_ = new T();
  25.         ::atexit(Destroy);
  26.     }
  27.     static void Destroy() {
  28.         delete value_;
  29.     }

  30. private:

  31.     static pthread_once_t ponce_;
  32.     static T* value_;


  33. };

  34. template <typename T>
  35. pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;

  36. template <typename T>
  37. T* Singleton<T>::value_ = NULL;


  38. class AA {
  39. public:
  40.     void show() { cout << "a" ;}
  41. };

  42. int main(int argc, char* argv[]) {

  43.     AA *pa = Singleton<AA>::instance();
  44.     pa->show();
  45.     return 0;
  46. }

阅读(999) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~