Resource Acquisition Is Initialization
lastmod 2024-11-28created 2015-05-285 edits
RAII is an idiom commonly used in C++: a technique that releases a resource when the object using it goes out of scope, so that the resource is used safely. It relies on the principle that in C++, resources allocated on the heap are not released unless explicitly freed, whereas for resources allocated on the stack, the memory is freed and the destructor is called when their scope ends.
It was originally a technique used to prepare for cases where control flow changes unexpectedly, for example due to an exception.
RAII and the Rust/Linux illusion
This post was written after watching the dispute between Rust developers and existing Linux developers. Different developers can have different coding styles, but the Linux project has a history of already excluding C++ and thereby avoiding its code style and structure (RAII).
The way the code Asahi Lina mentioned works is too slow when the program exits, and it conflicts with batching, the most fundamental approach to building performance-oriented software. For example, batching with memory regions lets multiple lifetimes be coordinated into one, so RAII is not needed.
Here are materials that back up my argument. All of them explain why batching is good:
- Casey Muratori | Smart-Pointers, RAII, ZII? Becoming an N+2 programmer
- CppCon 2014: Mike Acton "Data-Oriented Design and C++"
- Modern Systems Programming: Rust and Zig - Aleksey Kladov
Therefore, I think Linux should never adopt RAII.