Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # RAII (Resource Acquisition Is Initialization) A comprehensive guide to **RAII (Resource Acquisition Is Initialization)**, the core resource management idiom in C++, covering its principles, exception safety via stack unwinding, standard library examples, and custom wrapper implementation. ## 1. What Is RAII? **RAII (Resource Acquisition Is Initialization)** is a foundational C++ design idiom that **binds the lifecycle of any manually managed resource (heap memory, file descriptors, mutex locks, network sockets) to the lifetime of a stack-allocated local object**. - **Resource Acquisition = Constructor:** The resource is acquired during object initialization (`new`, `open()`, `lock()`, etc.). - **Resource Release = Destructor:** When the stack-allocated local object leaves its lexical scope (`{ ... }`), the compiler **automatically invokes its destructor**, which releases the resource (`delete`, `close()`, `unlock()`, etc.). > **Core Guarantee (Deterministic Destruction):** > In C++, a stack-allocated local object is guaranteed to execute its destructor immediately upon exiting the block (`{ ... }`) in which it was declared. Even if the developer forgets to call cleanup functions (`delete`, `close()`, `unlock()`), resource leaks are prevented by design. --- ## 2. Why Use RAII Instead of Manual Cleanup? (Stack Unwinding & Exception Safety) Placing manual `delete` or `close()` calls at the bottom of a function breaks down as soon as an **early `return`**, `break`, or **exception (`throw`)** occurs. ### 1. Pitfalls of Manual Resource Management (Resource Leaks) ```cpp void processFileManual(const std::string &filename, bool earlyExit) { int *buffer = new int[1024]; // Manual heap allocation if (earlyExit) { return; // Forgot delete[] on early return -> Memory leak! } mightThrowException(); // If an exception is thrown here, execution jumps out -> Memory leak! delete[] buffer; // Only reached on the normal execution path } ``` ### 2. How RAII Solves This (Stack Unwinding) Whether a function exits normally, returns early, or **unwinds the call stack due to an uncaught exception (Stack Unwinding)**, the C++ runtime guarantees that the destructors of all constructed local stack objects are **called in reverse order of construction**. ```cpp #include #include #include std::mutex mtx; void processFileRAII(const std::string &filename, bool earlyExit) { std::lock_guard lock(mtx); // 1. Constructor acquires mtx.lock() std::ifstream file(filename); // 2. Constructor opens file auto buffer = std::make_unique(1024); // 3. Constructor allocates heap array (new[]) if (earlyExit) { return; // On early return, destructors run in reverse order: // buffer (~unique_ptr) -> file (~ifstream) -> lock (~lock_guard), // automatically calling delete[], close(), and unlock()! } mightThrowException(); // Even if an exception is thrown (Stack Unwinding), all three destructors // run automatically, preventing memory leaks, file handle leaks, and deadlocks! } ``` --- ## 3. Representative RAII Classes in the C++ Standard Library Core components across the C++ Standard Library are built on RAII: | Resource Type | Standard Library RAII Classes | Constructor Action (Acquire) | Destructor Action (Automatic Cleanup) | | :--- | :--- | :--- | :--- | | **Dynamic Memory (Heap)** | `std::unique_ptr`
`std::shared_ptr` | Takes ownership of heap pointer | **Automatically calls `delete` / `delete[]`** (see [Smart Pointers]({{< relref "/programming/cpp/primer/smart-pointers.md" >}})) | | **Dynamic Containers** | `std::vector`
`std::string` | Allocates internal heap buffer | **Automatically frees internal heap buffer** | | **File Handles / Descriptors** | `std::ifstream`
`std::ofstream`
`std::fstream` | Opens file (`file.open()` → calls OS `open` under the hood) | **Automatically calls `file.close()`** (releases OS `fd`, see [The IO Library]({{< relref "/programming/cpp/primer/io-library.md" >}})) | | **Mutex Locks** | `std::lock_guard`
`std::unique_lock`
`std::scoped_lock` | Acquires mutex lock (`mtx.lock()`) | **Automatically calls `mtx.unlock()`** (prevents deadlocks on exception/early return) | --- ## 4. Implementing a Custom RAII Wrapper Class When working with C APIs or OS system calls (such as a POSIX file descriptor `int fd` from `open()` or a `FILE*` from `fopen()`), wrapping the raw handle in a small RAII class ensures deterministic cleanup. ### Important: Preventing Accidental Copies (`= delete`) If an RAII object is naively shallow-copied, both objects will hold the same underlying handle (`fd` or pointer) and both destructors will attempt to release it, causing a **Double Free / Double Close** bug. Therefore, an exclusive-ownership RAII class should **delete its copy constructor and copy-assignment operator (`= delete`)**. ```cpp #include #include #include // Custom RAII wrapper managing a POSIX file descriptor (int fd) class FileDescriptor { public: // 1. Constructor: Acquire resource (open file) explicit FileDescriptor(const char *path, int flags) : fd_(::open(path, flags)) { if (fd_ < 0) { throw std::runtime_error("Failed to open file"); } } // 2. Destructor: Automatically release resource (calls ::close when leaving scope) ~FileDescriptor() { if (fd_ >= 0) { ::close(fd_); } } // 3. Disable copy construction and copy assignment to prevent Double Close FileDescriptor(const FileDescriptor &) = delete; FileDescriptor &operator=(const FileDescriptor &) = delete; int get() const { return fd_; } private: int fd_ = -1; }; void useCustomRAII() { FileDescriptor fd("data.bin", O_RDONLY); // Perform read() operations using fd.get()... } // Leaving scope automatically invokes ~FileDescriptor(), calling ::close(fd_)! ```