Search CTRL + K

Resource Acquisition is Initialization

RAII(Resource Acquisition is Initialization),也叫 SBRM(Scope-Bound Resource Management) 是一种依赖于编程语言的特性,是指将 资源(指需要在使用前获取的东西,比如一块内存、线程、socket、文件、锁、磁盘空间和数据库连接等) 的生命周期绑定到一个对象上。

对象创建好后其绑定的资源也准备就绪,对象生命周期结束,对象销毁时其绑定的资源也按初始化顺序的逆序销毁。若资源获取失败,也能保证部份获取的资源按照初始化顺序的逆序释放。

目前 C++、Rust 提供该能力。


Resource Acquisition Is Initialization or RAII, is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.[1]

It's a really terrible name for an incredibly powerful concept, and perhaps one of the number 1 things that C++ developers miss when they switch to other languages. There has been a bit of a movement to try to rename this concept as Scope-Bound Resource Management, though it doesn't seem to have caught on just yet.[2]

RAII guarantees that the resource is available to any function that may access the object (resource availability is a class invariant, eliminating redundant runtime tests). It also guarantees that all resources are released when the lifetime of their controlling object ends, in reverse order of acquisition. Likewise, if resource acquisition fails (the constructor exits with an exception), all resources acquired by every fully-constructed member and base subobject are released in reverse order of initialization. This leverages the core language features (object lifetime, scope exit, order of initialization and stack unwinding) to eliminate resource leaks and guarantee exception safety.[1:1]


  1. https://en.cppreference.com/w/cpp/language/raii ↩︎ ↩︎

  2. https://stackoverflow.com/a/18054738 ↩︎