muduo/base库学习笔记(7)-----Singleton类

Singleton

muduo/base库学习笔记(7)-----Singleton类

成员函数的实现

static T& instance()的实现

 static T& instance()
  {
  //表明init函数只能调用一次
    pthread_once(&ponce_, &Singleton::init);
    assert(value_ != NULL);
    return *value_;
  }

static void init()函数的实现

static void init()
  {
    value_ = new T();
    
    if (!detail::has_no_destroy<T>::value)
    {
    //登记销毁函数,在程序接受的时候会调用destroy函数
      ::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;
  
    //删除value变量的空间
    delete value_;
    value_ = NULL;
  }