C++中局部變量在做用域裏的構造和析構行爲,爲資源的管理提供了靈活安全的解決之道。
下面以多線程的鎖來舉例
ios
#ifndef LOCK_H
#define LOCK_H
class Lock
{
public:
Lock(Mutex &m);
~Lock();
Mutex *mutex;
};
#endif // LOCK_H#include "lock.h"Lock::Lock(Mutex &m):mutex(&m){mutex->lock();//加鎖}Lock::~Lock()
{mutex->unlock();//解鎖}#include <iostream>#include "lock.h"using namespace std;void makeLock(Mutex &m);int main(){cout << "Hello World!" << endl;return 0;}void makeLock(Mutex &m){Lock l(m);//dosomething...拋出異常也不會致使鎖不能解開
}