gpt4 book ai didi

c++ - lock_guard 是 RAII 实现还是用于实现 RAII?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:43 26 4
gpt4 key购买 nike

Wikipedia (和其他一些来源)指出:

In RAII, holding a resource is tied to object lifetime: resource allocation (acquisition) is done during object creation (specifically initialization), by the constructor, while resource deallocation (release) is done during object destruction, by the destructor. If objects are destructed properly, resource leaks do not occur.

但是,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)
}

我为 lock_guard 找到的定义还引用它是“RAII 风格”:

The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.

举个例子,RAII是在mutex类中实现的,还是在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;
};

mutex_guard 的一个实例被创建时,它获取锁或者失败(如果 mutex::acquire 抛出)。如果它确实成功了,守卫对象将被完全实例化,并且保证调用它的析构函数。因此,如果互斥锁成功获取,则对 mutex::release 的配对调用是有保证的。

规范实现使用保证完全构建的对象在离开作用域时总是被销毁以确保获取的资源总是被释放。从这个意义上讲,它使用对象和实例生命周期上的标准保证来实现 RAII 习惯用法的要求。

关于c++ - lock_guard 是 RAII 实现还是用于实现 RAII?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com