On this page
  1. RAII & Destructors
  2. Overview
  3. Notes & Pitfalls
  4. Example

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

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

Related notes