fot*_*nus 1 c c++ design-patterns raii
维基百科(以及其他一些消息来源)指出:
在RAII中,持有资源与对象生存期相关联:资源分配(获取)在对象创建(特别是初始化)期间由构造函数完成,而资源释放(释放)在对象销毁期间由析构函数完成.如果对象被正确销毁,则不会发生资源泄漏.
但是,wiki上的示例显示的代码根本没有向我们展示对象的构造函数/析构函数:
#include <string>
#include <mutex>
#include <iostream>
#include <fstream>
#include <stdexcept>
void write_to_file (const std::string & message) {
// mutex to protect file access
static std::mutex mutex;
// lock mutex before accessing file
std::lock_guard<std::mutex> lock(mutex);
// try to open file
std::ofstream file("example.txt");
if (!file.is_open())
throw std::runtime_error("unable to open file");
// write message to file
file << message << std::endl;
// file will be closed 1st when leaving scope (regardless of exception)
// mutex will be unlocked 2nd (from lock destructor) when leaving
// scope (regardless of exception)
}
Run Code Online (Sandbox Code Playgroud)
我找到的lock_guard的定义也引用了它是"RAII风格":
类lock_guard是一个互斥包装器,它提供了一种方便的RAII风格机制,用于在范围块的持续时间内拥有互斥锁.
在这个例子中,RAII是在互斥类或lock_guard类中实现的?或者根本没有在课堂上实现?
RAII是C++中构造函数和析构函数的用法,用于确保成功的获取操作保证被撤消.典型的例子是锁定获取和释放.
class mutex_guard {
public:
explicit mutex_guard(mutex& lock): m_lock(lock) {
m_lock.acquire();
}
~mutex_guard() { m_lock.release(); }
private:
mutex& m_lock;
};
Run Code Online (Sandbox Code Playgroud)
mutex_guard创建实例时,它会获取锁定或失败(如果mutex::acquire抛出).如果它成功,则完全实例化保护对象,并保证它的析构函数被调用.因此,如果成功获取互斥锁,mutex::release则保证配对的被叫.
规范实现使用保证完全构造的对象在离开范围时将始终被破坏以确保始终释放所获取的资源.从这个意义上讲,它使用对象和实例生命周期的标准保证来实现RAII习语的要求.