维基百科 (和其他一些来源)指出:
在RAII中,保存资源与对象生存期相关联:资源分配(获取)是在对象创建(特别是初始化)期间、构造函数完成的,而资源释放( creation )则是在对象销毁和析构函数期间完成的。如果正确销毁对象,则不会发生资源泄漏。
但是,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)
}
我为守卫找到的定义也引用了“RAII风格”:
类lock_guard是一个互斥包装器,它提供了一种方便的RAII风格的机制,用于在作用域块的持续时间内拥有互斥。
在示例中,RAII是在互斥类上实现的,还是在lock_guard类中实现的?还是根本没有在类上实现?
发布于 2015-05-16 22:51:02
是lock_guard
在您发布的代码片段中提供了用于同步的RAII 。mutex
自己并没有遵循RAII的成语。RAII不必由单独的对象提供。例如,std::ofstream
为文件输出操作提供了功能,为文件状态提供了RAII 。这是留给设计师的自由吗。
RAII =资源获取是初始化
ie对象的创建意味着资源的获取,对象的破坏则意味着资源的破坏。如果你是在其他地方进行获取或破坏,那么你不是在使用RAII。
发布于 2015-05-16 22:40:50
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;
};
创建mutex_guard
实例时,它获取锁或失败(如果mutex::acquire
抛出)。如果成功,将完全实例化守护对象,并保证调用它的析构函数。因此,如果成功地获得互斥对象,则保证对mutex::release
的调用。
规范的实现是使用这样的保证:当一个完整构造的对象离开作用域时,它总是被销毁,以确保所获得的资源总是被释放。在这个意义上,它使用对象和实例生命周期上的标准保证来实现RAII成语的需求。
https://stackoverflow.com/questions/30281441
复制相似问题