什么是资源获取初始化(RAII)?


当前回答

RAII类有三个部分:

该资源在析构函数中被放弃 类的实例是堆栈分配的 资源是在构造函数中获取的。这部分是 可选,但很常见。

RAII代表“资源获取是初始化”。RAII的“资源获取”部分是你开始某些必须在之后结束的内容,例如:

打开文件 分配内存 获取锁

“is initialization”部分意味着获取发生在类的构造函数内部。

https://www.tomdalling.com/blog/software-design/resource-acquisition-is-initialisation-raii-explained/

其他回答

这是一个编程习语,简单地说就是您

将资源封装到类中(类的构造函数通常——但不一定是**——获取资源,其析构函数总是释放它) 通过类的本地实例*使用资源 当对象超出作用域时,资源将自动释放

这保证了在使用资源时无论发生什么,它最终都将被释放(无论是由于正常返回、销毁包含的对象,还是抛出异常)。

这是c++中广泛使用的良好实践,因为除了是处理资源的安全方式外,它还使您的代码更加干净,因为您不需要将错误处理代码与主要功能混合在一起。

*更新:“local”可以是一个局部变量,也可以是一个类的非静态成员变量。在后一种情况下,成员变量被初始化并与其所有者对象一起销毁。

** Update2:正如@sbi指出的那样,虽然资源通常是在构造函数内部分配的,但也可以在构造函数外部分配并作为参数传入。

Manual memory management is a nightmare that programmers have been inventing ways to avoid since the invention of the compiler. Programming languages with garbage collectors make life easier, but at the cost of performance. In this article - Eliminating the Garbage Collector: The RAII Way, Toptal engineer Peter Goodspeed-Niklaus gives us a peek into the history of garbage collectors and explains how notions of ownership and borrowing can help eliminate garbage collectors without compromising their safety guarantees.

对于一个非常强大的概念来说,这是一个非常糟糕的名字,而且可能是c++开发人员在转向其他语言时最容易忽略的事情之一。有一些人试图将这个概念重命名为作用域绑定资源管理(Scope-Bound Resource Management),尽管它似乎还没有流行起来。

When we say 'Resource' we don't just mean memory - it could be file handles, network sockets, database handles, GDI objects... In short, things that we have a finite supply of and so we need to be able to control their usage. The 'Scope-bound' aspect means that the lifetime of the object is bound to the scope of a variable, so when the variable goes out of scope then the destructor will release the resource. A very useful property of this is that it makes for greater exception-safety. For instance, compare this:

RawResourceHandle* handle=createNewResource();
handle->performInvalidOperation();  // Oops, throws exception
...
deleteResource(handle); // oh dear, never gets called so the resource leaks

用RAII这个

class ManagedResourceHandle {
public:
   ManagedResourceHandle(RawResourceHandle* rawHandle_) : rawHandle(rawHandle_) {};
   ~ManagedResourceHandle() {delete rawHandle; }
   ... // omitted operator*, etc
private:
   RawResourceHandle* rawHandle;
};

ManagedResourceHandle handle(createNewResource());
handle->performInvalidOperation();

在后一种情况下,当抛出异常并展开堆栈时,局部变量将被销毁,这确保了我们的资源被清理并且不会泄漏。

《c++ Programming with Design Patterns Revealed》一书将RAII描述为:

获取所有资源 利用资源 释放资源

在哪里

资源被实现为类,所有指针都有类包装器(使它们成为智能指针)。 通过调用构造函数获取资源,通过调用析构函数隐式释放资源(与获取资源的顺序相反)。

“RAII”代表“资源获取即初始化”,实际上是一个用词不当的词,因为它所关心的不是资源获取(和对象的初始化),而是释放资源(通过销毁对象)。 但RAII是我们得到的名字,并且一直沿用。

从本质上讲,这个习语的特点是将资源(内存块、打开的文件、解锁的互斥对象、you-name-it)封装在本地、自动对象中,并且当对象在其所属作用域的末尾被销毁时,该对象的析构函数会释放资源:

{
  raii obj(acquire_resource());
  // ...
} // obj's dtor will call release_resource()

当然,对象并不总是本地自动对象。他们也可以是一个阶级的成员:

class something {
private:
  raii obj_;  // will live and die with instances of the class
  // ... 
};

如果这样的对象管理内存,它们通常被称为“智能指针”。

There are many variations of this. For example, in the first code snippets the question arises what would happen if someone wanted to copy obj. The easiest way out would be to simply disallow copying. std::unique_ptr<>, a smart pointer to be part of the standard library as featured by the next C++ standard, does this. Another such smart pointer, std::shared_ptr features "shared ownership" of the resource (a dynamically allocated object) it holds. That is, it can freely be copied and all copies refer to the same object. The smart pointer keeps track of how many copies refer to the same object and will delete it when the last one is being destroyed. A third variant is featured by std::auto_ptr which implements a kind of move-semantics: An object is owned by only one pointer, and attempting to copy an object will result (through syntax hackery) in transferring ownership of the object to the target of the copy operation.