首页 > 代码库 > 简单的单例类和智能指针
简单的单例类和智能指针
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_; };
简单的单例类和智能指针
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。