muduo:Singleton类,单例模式
来源:互联网 发布:微信加友软件免费下载 编辑:程序博客网 时间:2024/05/01 17:59
>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;
0 0
- muduo:Singleton类,单例模式
- muduo库源码解析:单例模式singleton
- 【muduo】单例模式
- 单例(Singleton)模式
- singleton 单例模式
- Singleton单例模式
- Singleton(单例)模式
- Singleton 单例模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- Singleton(单例)模式
- Singleton(单例)模式
- 单例模式(Singleton)
- 单例模式(Singleton)
- 单例模式Singleton
- Singleton (单例模式)
- Singleton单例模式
- 单例模式----SingleTon
- IOS-TextField详解
- dp 杂练/专练 round2
- solr5.5.0服务启动与停止
- 文件属性和管理
- 2016-06-20-课程设计日志
- muduo:Singleton类,单例模式
- c语言学习笔记32
- IOS状态栏和导航栏的控制问题
- 用户管理
- 国外免费版杀毒软件
- 今夜有感
- Redis-server在windows下闪退
- Struts2+Spring3+Hibernate4+JavaEE6 配置
- Java中动态代理使用