首页 > 代码库 > 简单的单例类和智能指针

简单的单例类和智能指针

1.一个简单的单例类:

class Singleton
{
    public:
        static Singleton *getInstance()
        {
            if(pInstance_ == NULL){
                mutex_.lock();
                if(pInstance_ == NULL){
                    sleep(1);
                    pInstance_ = new Singleton;
                }
                mutex_.unlock();
            }
            return pInstance_;
        }
    private:
        Singleton(){}

        static Singleton *pInstance_;
        static MutexLock mutex_;
};

Singleton *Singleton::pInstance_ = NULL;
MutexLock Singleton::mutex_;

互斥锁类:

class MutexLock
{
    public:
        MutexLock()
        {
            if(pthread_mutex_init(&lock_, NULL)){
                throw std::runtime_error("init lock fail!");
            }
        }
        
        ~MutexLock()
        {
            if(pthread_mutex_destroy(&lock_)){
                throw std::runtime_error("destroy lock fail");
            }
        }

        void lock(){
            if(pthread_mutex_lock(&lock_)){
                throw std::runtime_error("lock failed!");
            }
        }

        void unlock(){
            if(pthread_mutex_unlock(&lock_)){
                throw std::runtime_error("unlock failed!");
            } 
        }

        //这里提供指针是为了cond的wait操作
        //这里不能为const
        pthread_mutex_t *getMutexLockPtr()
        {
            return &lock_;
        }

    private:
        pthread_mutex_t lock_;
};


 一个简单的智能指针类:

class SmartPtr
{
    public:
        SmartPtr(Animal *ptr):ptr_(ptr)
              {
               }
        ~SmartPtr()
         {
        delete ptr_;
         }
        Animal *operator->()
            {
           return ptr_;
          }
        const Animal *operator->() const
        {
           return ptr_;
          }

        Animal &operator*()
            {
               return *ptr_;
              }
        const Animal &operator*() const
          {
            return *ptr_;
              }
    private:
        DISALLOW_COPY_AND_ASSIGN(SmartPtr);
        T *ptr_;
};


简单的单例类和智能指针