muduo:Singleton类,单例模式
2016-06-20 23:06
330 查看
>Singleton类:
#include <boost/noncopyable.hpp> #include <assert.h> #include <stdlib.h> // atexit #include <pthread.h> template<typename T> struct has_no_destroy { template <typename C> static char test(typeof(&C::no_destroy)); // or decltype in C++11 template <typename C> static int32_t test(...); const static bool value = sizeof(test<T>(0)) == 1; }; template<typename T> class Singleton : boost::noncopyable { public: static T& instance() //static,保证可以通过类作用域运算符进行调用。 { //pthread_once()函数,在多线程中,保证某个函数只被执行一次。<pthread.h> pthread_once(&ponce_, &Singleton::init); assert(value_ != NULL); return *value_; } private: Singleton(); ~Singleton(); static void init() { value_ = new T(); if (has_no_destroy<T>::value) { //register a function to be called at normal process termination //注册一个函数,在程序终止时执行。 atexit(destroy); } } static void destroy() { //一种技巧,在编译期间检查不完全类型错误。 typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; T_must_be_complete_type dummy; (void) dummy; delete value_; value_ = NULL; } private: //注意是static静态类型,确保只有一个并在类的作用于运算符进行初始化。 static pthread_once_t ponce_; static T* value_; }; template<typename T> pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT; //创建一个全局的Singleton<T>::ponce_变量,体现static的作用。 template<typename T> T* Singleton<T>::value_ = NULL;
相关文章推荐
- 六轴传感器MPU6050
- 文件属性和管理
- solr5.5.0服务启动与停止
- JSON
- Wine虚拟技术及其使用
- RAM,ROM和Flash memory等存储器的比较
- android UI TextView setText显示服务器返回数据
- bzoj2054 疯狂的馒头
- HTML5多媒体audio和video(一)
- JSON clone 实现
- [BZOJ4537] [HNOI/AHOI2016] 最小公倍数 - 分块 - 并查集
- BZOJ_1614_ [Usaco2007_Jan]_Telephone_Lines_架设电话线_(二分+最短路_Dijkstra/Spfa)
- MySQL查询数据表的Auto_Increment(自增id)
- Scroller的使用,让View随心所欲的移动
- HTML表单标签
- 将应用交付服务引入到OpenStack-【中国IC微专栏】2016.6.16
- TabHost
- PHP 浏览器禁用cookie,解决session变量不能传值
- 怎么用maven创建一个Java Web项目?
- mysql共享锁与排他锁