class Mutex{}; void lock(Mutex* mutex) {} //锁住资源 void unlock(Mutex* mutex) {} //释放资源 class MyLock { public: explicit MyLock(Mutex *mutex) :m_mutex(mutex) { lock(m_mutex); } ~MyLock() {unlock(m_mutex);} private: Mutex *m_mutex; };调用
void process() { Mutex mutex; MyLock mylock(&mutex); //process } //离开作用域,mylock执行析构函数,释放mutex管理对象被复制了,会出现什么情况?
void process() { Mutex mutex; MyLock mylock(&mutex); MyLock mylock2(mylock); //调用默认拷贝构造函数,指向同一个资源 //process } //离开作用域,mylock和mylock2执行析构函数,释放mutex两次如何解决RAII对象被复制的情况呢?
class MyLock : private Uncopyable {};②对底层使用“引用计数法”
class Mutex{}; void lock(Mutex* mutex) {} //锁住资源 void unlock(Mutex* mutex) {} //释放资源 class MyLock { public: explicit MyLock(Mutex *mutex) :m_mutexPtr(mutex, unlock) { lock(m_mutexPtr.get()); } //~MyLock() {unlock(m_mutex);} //不用再定义析构函数,直接通过m_mutexPtr删除器释放资源 private: std::tr1::shared_ptr<Mutex> m_mutexPtr; };调用
void process() { Mutex mutex; MyLock mylock(&mutex); //m_mutexPtr引用计数为2 MyLock mylock2(mylock); //调用默认拷贝构造函数,指向同一个资源,m_mutexPtr引用计数为2 //process } //离开作用域,成员对象mylock和mylock2的智能指针对象都执行析构函数且引用计数减为0,则调用删除器unlock()函数解除锁③复制底部资源
条款14:在资源管理类中小心coping行为,布布扣,bubuko.com
原文地址:http://blog.csdn.net/hualicuan/article/details/27328573