【muduo】单例模式
来源:互联网 发布:阿里云服务器关闭快照 编辑:程序博客网 时间:2024/05/22 15:11
Singleton.h
// Use of this source code is governed by a BSD-style license// that can be found in the License file.//// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_SINGLETON_H#define MUDUO_BASE_SINGLETON_H#include <boost/noncopyable.hpp>#include <assert.h>#include <stdlib.h> // atexit#include <pthread.h>namespace muduo{namespace detail{// This doesn't detect inherited member functions!// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functionstemplate<typename T>struct has_no_destroy{#ifdef __GXX_EXPERIMENTAL_CXX0X__ // C++11 利用decltype来进行类型推断 template <typename C> static char test(decltype(&C::no_destroy));#else // typeof 类型推断 template <typename C> static char test(typeof(&C::no_destroy));#endif template <typename C> static int32_t test(...); const static bool value = sizeof(test<T>(0)) == 1;};}// 单例模式的共同基类template<typename T>class Singleton : boost::noncopyable{ public: // 利用 pthread_once保证只有一个实例被创建 static T& instance() { pthread_once(&ponce_, &Singleton::init); assert(value_ != NULL); return *value_; } private: Singleton(); ~Singleton(); // 只有单例模式第一次被创建的时候被执行 static void init() { value_ = new T(); if (!detail::has_no_destroy<T>::value) { ::atexit(destroy); } } // 销毁单例模式中的唯一变量 static void destroy() { // //类T一定要完整,否则delete时会出错,这里当T不完整时将数组的长度置为-1,这是不合法的,因而会报错 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 pthread_once_t ponce_; static T* value_;};template<typename T>pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT;template<typename T>T* Singleton<T>::value_ = NULL;}#endif
阅读全文
0 0
- 【muduo】单例模式
- muduo:Singleton类,单例模式
- muduo库源码解析:单例模式singleton
- Muduo库源码分析(8):单例模式实现
- muduo网络库:单例设计
- muduo库阅读(8)——单件模式的线程局部存储
- 单例、单例模式
- muduo源码分析--Reactor模式在muduo中的使用
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 0724JS Link
- HDU5531(三分)
- 迭代器与yield return
- 寄生组合式继承的相关问题
- servlet容器和servlet引擎的联系
- 【muduo】单例模式
- LintCode C++代码Two Sum
- 【项目管理】 使用IntelliJ IDEA 将项目发布(提交)到GitLab
- xmind文件转excel文件,java实现
- Iframe跨域父子页面调用
- 文章标题
- JSP--第十二天
- Spring aop--几种不同的使用方式
- 布局引用引起错误