muduo之Singleton
生活随笔
收集整理的這篇文章主要介紹了
muduo之Singleton
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ? ?muduo中的單例模式
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 "muduo/base/noncopyable.h"#include <assert.h> #include <pthread.h> #include <stdlib.h> // atexitnamespace muduo {namespace detail { // This doesn't detect inherited member functions! // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions template<typename T> struct has_no_destroy {//decltype選擇并返回操作數(shù)的數(shù)據(jù)類型template <typename C> static char test(decltype(&C::no_destroy));template <typename C> static int32_t test(...);const static bool value = sizeof(test<T>(0)) == 1;//判斷如果是類的話,是否有no_destroy方法 }; } // namespace detailtemplate<typename T> class Singleton : noncopyable {public:Singleton() = delete;~Singleton() = delete;static T& instance() //static,保證可以通過類作用域運(yùn)算符進(jìn)行調(diào)用{//pthread_once()函數(shù),在多線程中,保證某個(gè)函數(shù)只被執(zhí)行一次。<pthread.h>pthread_once(&ponce_, &Singleton::init); assert(value_ != NULL);return *value_;}private:static void init(){value_ = new T(); //根據(jù)傳入的類型進(jìn)行newif (!detail::has_no_destroy<T>::value)//當(dāng)參數(shù)是類且沒有"no_destroy"方法才會注冊atexit的destroy{//注冊一個(gè)函數(shù),在程序終止時(shí)執(zhí)行::atexit(destroy);//登記atexit時(shí)調(diào)用的銷毀函數(shù),防止內(nèi)存泄漏}}static void destroy(){用typedef定義了一個(gè)數(shù)組類型,數(shù)組的大小不能為-1,利用這個(gè)方法,如果是不完全類型,編譯階段就會發(fā)現(xiàn)錯誤定義一個(gè)char數(shù)組類型 T_MUST_BE_COMPELET_TYPE :char[-1]---如果T只聲明沒有定義-不完全類型 ; char[1]--T是完全類型,即有定義,delete操作,可以調(diào)用析構(gòu)函數(shù),沒定義就沒有析構(gòu)函數(shù),delete就不會調(diào)用析構(gòu)函數(shù)了typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];//要銷毀這個(gè)類型,這個(gè)類型必須是完全類型T_must_be_complete_type dummy; (void) dummy;delete value_;value_ = NULL;}private://pthread_once參數(shù)static pthread_once_t ponce_;static T* value_;//指向一個(gè)實(shí)例 };//static需要在類外進(jìn)行初始化 template<typename T>//創(chuàng)建一個(gè)全局的Singleton<T>::ponce_變量,體現(xiàn)static的作用 pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT; //ponce_初始化template<typename T> T* Singleton<T>::value_ = NULL;} // namespace muduo#endif // MUDUO_BASE_SINGLETON_H?
總結(jié)
以上是生活随笔為你收集整理的muduo之Singleton的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: muduo之CountDownLatch
- 下一篇: muduo之Atomic