简单的单例类和智能指针
来源:程序员人生 发布时间:2014-10-13 06:43:22 阅读次数:3286次
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_;
};
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠