On this page
RAII & Destructors
Prev: References & Rvalues | Up: builtins | Next: Templates
Rel: RAII, Smart Pointers & Lifetime, std::unique_ptr, RAII Resource Wrapper Tutorial
Ref: cppreference — RAII
Tags: #public #prog #cpp #builtins #raii #tier/core
Overview
RAII (Resource Acquisition Is Initialization) is C++'s foundational idiom: tie every resource's lifetime (heap memory, file descriptors, mutex locks, sockets) to an object's stack scope. The constructor acquires the resource, and the destructor (~T()) deterministically releases it when the object leaves scope—even during stack unwinding from an exception.
Notes & Pitfalls
- Tie every resource lifetime to a stack object: Memory (
unique_ptr), locks (scoped_lock), and files (ifstream) release deterministically even when exceptions unwind the stack. - Follow the Rule of Zero: Compose stdlib RAII types so you never write manual
new/deleteor custom destructors.
Example
#include <cassert>
#include <fstream>
int main() {
{
std::ofstream out("raii_demo.tmp");
out << "auto-closed on scope exit";
} // destructor flushes and closes file automatically
assert(true);
}
Linked from
- tuts/cpp/builtins
- tuts/cpp/builtins/classes_and_virtual
- tuts/cpp/builtins/references_and_rvalues
- tuts/cpp/builtins/templates
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime
- tuts/cpp/language_and_raii/value_categories_and_move_semantics
- tuts/cpp/stdlib/concurrency
- tuts/cpp/stdlib/concurrency/jthread
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard
- tuts/cpp/stdlib/io_and_filesystem
- tuts/cpp/stdlib/io_and_filesystem/iostream
- tuts/cpp/stdlib/memory
- tuts/cpp/stdlib/memory/unique_ptr
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper
Related notes
- tuts/cpp/builtins/references_and_rvalues Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/templates Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime Linked here; links to this page; shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper Linked here; links to this page; shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/stdlib/memory/unique_ptr Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/language_and_raii/value_categories_and_move_semantics links to this page; shared tags: #cpp, #prog, #raii, #tier
- tuts/cpp/stdlib/concurrency/jthread links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard links to this page; shared tags: #cpp, #prog, #tier