我浅显的理解就是资源的获取(锁,数据库链接,文件等)和释放分别在构造函数和析构函数中实现。由此想到了之前的一篇文章C++简洁实现线程安全单例类里面的两个类:AutoLock和Mutex,它们就是典型的RAII类,Mutex的构造函数中init了一个mutex,析构函数中则destroy了它,AutoLock在构造函数中获得了一个mutex,在析构函数中则释放了它,看代码就了然。
#define DISABLE_COPY_AND_ASSIGN(T) \
T(const T &); \
T& operator=(const T &)
struct Recursive {};
class Mutex {
public:
Mutex() {
pthread_mutex_init(&_mutex, NULL);
}
explicit Mutex(Recursive) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
~Mutex() {
pthread_mutex_destroy(&_mutex);
}
int lock() {
return pthread_mutex_lock(&_mutex);
}
int trylock() {
return pthread_mutex_trylock(&_mutex);
}
int unlock() {
return pthread_mutex_unlock(&_mutex);
}
private:
pthread_mutex_t _mutex;
// RAII class should not be able to be copied
DISABLE_COPY_AND_ASSIGN(Mutex);
};
template <class T>
class AutoLock {
public:
explicit AutoLock(T* t) : _t(t) {
_t.lock();
}
~AutoLock() {
_t.unlock();
}
private:
T* _t;
// RAII class should not be able to be copied
DISABLE_COPY_AND_ASSIGN(AutoLock);
};
其实在C++11中的std::mutex和std::unique_lock已经实现了上述两个类的功能,引用The C++ Programming Language 4th Edition中的代码:
mutex m; // used to protect access to shared data
// ...
void f()
{
unique_lock<mutex> lck {m}; // acquire the mutex m
// ... manipulate shared data ...
}
书中的解释是:
A thread will not proceed until lck’s constructor has acquired its mutex, m (§5.3.4).
The corresponding destructor releases the resource. So, in this example, unique_lock’s destructor
releases the mutex when the thread of control leaves f() (through a return, by “falling off the
end of the function,” or through an exception throw).
This is an application of the “Resource Acquisition Is Initialization” technique (RAII; §3.2.1.2, §13.3).
This technique is fundamental to the idiomatic handling of resources in C++.
Containers (such as vector and map), string, and iostream manage their
resources (such as file handles and buffers) similarly.