module_singleton_base.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #ifndef MODULE_SINGLETON_BASE_H
  2. #define MODULE_SINGLETON_BASE_H
  3. #include<mutex>
  4. template<typename T>
  5. class singleton_base
  6. {
  7. public:
  8. static T *instance()
  9. {
  10. if(nullptr != _instance)
  11. {
  12. return _instance;
  13. }
  14. std::lock_guard<std::mutex> ll(_mutex_singleton_base);
  15. if(nullptr == _instance)
  16. {
  17. _instance = new(std::nothrow) T();
  18. }
  19. return _instance;
  20. }
  21. protected:
  22. //使继承者无法public构造函数和析构函数
  23. singleton_base(){}
  24. //virtual ~singleton_base(){}
  25. private:
  26. //禁止拷贝构造和赋值运算符
  27. singleton_base(const singleton_base&){}
  28. singleton_base &operator=(const singleton_base&){}
  29. //它的唯一工作就是在析构函数中析构Singleton的实例,所以private
  30. class Garbo
  31. {
  32. public:
  33. ~Garbo()
  34. {
  35. if (singleton_base::_instance)
  36. {
  37. delete singleton_base::_instance;
  38. singleton_base::_instance = nullptr;
  39. }
  40. }
  41. };
  42. //定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数,我们不需要访问这个变量,所以不需要初始化
  43. static Garbo garbo;
  44. static T *_instance;
  45. static std::mutex _mutex_singleton_base;
  46. };
  47. template<typename T>
  48. T *singleton_base<T>::_instance = nullptr;
  49. template<typename T>
  50. std::mutex singleton_base<T>::_mutex_singleton_base;
  51. #endif // MODULE_SINGLETON_BASE_H