Programming Search⌘K

Conceptcore

Resource acquisition is initialization

Also called RAII, scope-bound resource management, SBRM, scoped resource management, deterministic cleanup.

RAII ties a resource to the lifetime of an object or a scope. The language releases the resource on every exit from the scope, also on an exception.

Applies to
core-languages

Idea

A program uses many things that it must give back: heap memory, file descriptors, sockets, locks, database transactions, temporary directories. Each of these is a resource. The release must happen exactly once, and it must happen on every path out of the code that uses the resource. A function that closes its file on its last line can still leak the file. An early return, a break out of a loop or an exception skips that line. A leaked lock is worse than leaked memory, because the next thread that asks for it waits forever.

Resource acquisition is initialization (RAII) binds the resource to the lifetime of an object. The constructor acquires the resource, and the destructor releases it. The object lives in a scope, and the language ends the lifetime of the object on every exit from that scope. So the release cannot be forgotten, and the programmer writes it once per kind of resource, not once per use.12 The term comes from C++, where the destructor of a local object runs when its block exits.3 Languages without destructors use a statement that marks the scope. Examples are with in Python, try-with-resources in Java, using in C# and JavaScript, and defer in Go.

class Connection:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("open", self.name)
        return self

    def __exit__(self, exc_type, exc, traceback):
        print("close", self.name)
        return False  # do not suppress the exception


def query(fail):
    with Connection("orders") as conn:
        if fail:
            raise RuntimeError("query failed")
        return "rows from " + conn.name


print(query(False))
try:
    query(True)
except RuntimeError as error:
    print("caught:", error)
Output
open orders
close orders
rows from orders
open orders
close orders
caught: query failed

The connection closes before the return hands its value to the caller, and it closes before the exception reaches the except clause. The function body has no close call and no finally block.

How it works

A scope has one entry and many exits. The compiler knows every exit: the end of the block, each return, break, continue and goto, and each point where an exception can leave. RAII asks the compiler, not the programmer, to put the release on each of them.

C++ states the rule for each transfer of control. Control can move from a point P to a point Q. Then each automatic variable that is active at P and not at Q is destroyed, in the reverse order of construction.56 An exception follows the same rule. On the way from the throw to the handler, stack unwinding destroys the automatic objects made since the try block began. Again the order is the reverse.7 A destructor runs implicitly when the block of its object exits and when a temporary dies. Destructors of thread and static objects run at thread exit and at program end.4

void add_order() {                      exit paths:
    lock_guard guard(m);   // 1             end of block      -> ~cache, ~log, ~guard
    Handle log("log");     // 2             return            -> ~cache, ~log, ~guard
    Handle cache("cache"); // 3             throw             -> ~cache, ~log, ~guard, then the handler
    ...                                     std::exit()       -> no destructors of locals
}

The order is the reverse of acquisition because a later resource can depend on an earlier one. A cache may write to the log while it shuts down, so the log must still be open. Rust uses the same order for local variables.14 Members are a different case. C++ destroys the bases and members of an object in the reverse order of their construction.4 Rust drops the fields of a struct in declaration order, after the drop method of the struct itself.14

Construction can fail halfway. If a constructor throws, C++ destroys only the subobjects whose construction has finished, and it never runs the destructor of the object itself.7 So a class that acquires two resources in its constructor should hold each one in a member that is itself an RAII object. Then a failure at the second acquisition still releases the first.

The languages fall into two families.

Destructor-bound. C++ and Rust attach the release to the type. Every value of the type releases its resource when it dies, wherever it lives. It can be a local variable, a member of another object or an element of a container. It can also be a heap object that a std::unique_ptr or a Box owns. The destructor of std::unique_ptr deletes the object it owns, and the destructor of std::lock_guard unlocks its mutex.1211 Ownership can move, so a function can make a resource and return it, and the scope of the caller then releases it. See Ownership and borrowing.

Statement-bound. Python, Java, C#, JavaScript, Go, Kotlin and Bash attach the release to a block in the code that uses the resource. The type only offers a release method: __exit__, close, Dispose, [Symbol.dispose]. The language rewrites the block into a try and finally. The Python reference gives this translation for with, and the JLS gives one for try-with-resources.1823 The object itself can outlive the block, in a closed state.

  1. SCOPED(acquire₁, …, acquireₙ, body) ▷ what with, using and try-with-resources do
  2. 1done ← empty stack
  3. 2try
  4. 3for i ← 1 to n do
  5. 4r ← acquireᵢ() ▷ a failure here skips the body
  6. 5push r on done
  7. 6body() ▷ may return, break or throw
  8. 7finally
  9. 8while done is not empty do
  10. 9r ← pop done ▷ reverse order of acquisition
  11. 10release r ▷ an error here must not stop the other releases

Line 10 hides a hard question: what happens when the release itself fails while another error is already in flight. Java closes every resource and adds each later exception to the suppressed list of the first one.23 The JavaScript proposal wraps the two errors in a SuppressedError.36 C++ destructors are noexcept unless they say otherwise, so an exception that leaves a destructor calls std::terminate.89 Python passes the exception to __exit__, which can suppress it by returning a true value.19

RAII covers the exits of a scope, not the end of the process. std::exit ends a C++ program without destroying automatic objects.6 std::process::exit and std::process::abort in Rust run no destructors.14 os.Exit in Go does not run deferred functions.33

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsent
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinStandard libraryThe use extension function runs a block on a Closeable and closes it whether or not the block throws; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: Try and finally that call close().
SQLDoes not applyThe database engine releases locks and cursors at the end of a statement or transaction; the statement itself holds no resource of the program. Alternative: A transaction that ends with COMMIT or ROLLBACK.
BashIdiom
PowerShellIdiomA try statement whose finally block calls Dispose(), and the clean block of an advanced function, which runs like a finally over begin, process and end; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup holds no resources.
CSSDoes not applyStyle rules hold no resources.
Regular expressionsDoes not applyA pattern holds no resources.

The example files run the same test in each language. They open two resources and leave once normally and once through an error. Then they print the order of the releases.

Language Verdict Construct
Python native with and context managers (__enter__, __exit__); contextlib.ExitStack for a list of resources1821
JavaScript native using declarations, Symbol.dispose and DisposableStack from the Explicit Resource Management proposal36
TypeScript native the JavaScript using declaration, with the Disposable interface
Java native try-with-resources on AutoCloseable2324
C absent no destructors; the goto cleanup idiom; the cleanup attribute of GCC and Clang is an extension39
C++ native destructors of automatic objects; std::lock_guard, std::unique_ptr, std::fstream4111213
C# native the using statement and the using declaration on IDisposable27
Go native defer runs a call when the surrounding function returns32
Rust native the Drop trait; every value is dropped at the end of its scope14
Kotlin stdlib the use extension function on Closeable35
PowerShell idiom try and finally that call Dispose(); the clean block of an advanced function40
Bash idiom trap ... EXIT in a subshell, so the trap runs when the subshell exits38
SQL n/a the database engine releases locks and cursors; a statement holds no resource of the program
Regex n/a a pattern holds no resources
HTML/CSS n/a markup and style hold no resources

C++ and Rust are the destructor-bound family. The release runs for every value of the type. A container of files closes all of them, and a struct that holds a lock guard unlocks when the struct dies. Rust adds std::mem::drop to end a value early, because a direct call of the drop method is a compile error (E0040).15 MutexGuard is the Rust lock guard: dropping it unlocks the mutex.17

Python, Java, C# and JavaScript use a statement that names the resource at the top of a block. Python calls __exit__ after the suite ends for any reason, once __enter__ has returned.18 Java closes the resources in the reverse order of initialization, and only those with a non-null value.23 C# disposes the variable of a using declaration at the end of its scope. It disposes several resources of one statement in reverse order.27 JavaScript disposes using bindings in reverse order when the block exits.36 Kotlin has no statement; use is a library function that runs a lambda and closes the receiver whether the lambda throws or not.35

Go binds the release to the function, not to a block. Each defer saves a call, and the deferred calls run in the reverse order when the function returns or panics.32 This is a coarser scope than a C++ block, and it causes the loop pitfall below.

C has no destructors and no finally. Programs write the releases by hand. A common form is a goto to a list of labels at the end of the function, in reverse order of acquisition. GCC has a cleanup attribute on a local variable. It runs a function when the variable goes out of scope, in reverse order of definition.39 It is a compiler extension, not standard C. The Clang that recorded these examples accepts it too.

Bash has no scopes with cleanup, but trap 'commands' EXIT runs the commands when the shell exits, and exit runs that trap first.38 A function whose body is a subshell ( ... ) therefore gets an EXIT trap that runs at the end of the function.

PythonGitHub
from contextlib import ExitStack, contextmanager


@contextmanager
def opened(path):
    print("open", path)
    try:
        yield path
    finally:
        print("close", path)


def copy(paths, fail):
    with ExitStack() as stack:
        handles = [stack.enter_context(opened(path)) for path in paths]
        if fail:
            raise OSError("disk full")
        print("copy", " -> ".join(handles))


copy(["source", "target"], fail=False)
try:
    copy(["source", "target"], fail=True)
except OSError as error:
    print("caught:", error)
Output
open source
open target
copy source -> target
close target
close source
open source
open target
close target
close source
caught: disk full
  • Verdict: native. The with statement calls __enter__ at the start of the block and __exit__ on every exit, also when an exception leaves the block.
  • @contextmanager turns a generator into a context manager. The code before yield acquires, and the finally after it releases.
  • ExitStack holds a list of managers whose number is known only at run time. It closes them in the reverse order of enter_context.
  • In the second call, the OSError passes through the with block. Both files close before the except clause prints the message.
#include <memory>
#include <mutex>
#include <print>
#include <stdexcept>
#include <string>
#include <utility>

class Handle {
public:
    explicit Handle(std::string name) : name_(std::move(name)) {
        std::println("acquire {}", name_);
    }
    ~Handle() { std::println("release {}", name_); }
    Handle(const Handle&) = delete;
    Handle& operator=(const Handle&) = delete;

private:
    std::string name_;
};

std::mutex orders_mutex;
int order_count = 0;

void add_order(bool fail) {
    std::lock_guard<std::mutex> guard(orders_mutex);
    Handle log("log");
    Handle cache("cache");
    if (fail) {
        throw std::runtime_error("bad order");
    }
    ++order_count;
}

int main() {
    add_order(false);
    try {
        add_order(true);
    } catch (const std::exception& error) {
        std::println("caught {}", error.what());
    }
    bool free_after_throw = orders_mutex.try_lock();
    std::println("mutex free after throw: {}", free_after_throw);
    if (free_after_throw) {
        orders_mutex.unlock();
    }
    auto buffer = std::make_unique<Handle>("buffer");
    std::println("orders: {}", order_count);
}
Output
acquire log
acquire cache
release cache
release log
acquire log
acquire cache
release cache
release log
caught bad order
mutex free after throw: true
acquire buffer
orders: 1
release buffer
  • Verdict: native. The destructor of each local object runs when its block exits, in the reverse order of construction. Here cache is released before log.
  • std::lock_guard locks the mutex in its constructor and unlocks it in its destructor. After the exception, try_lock succeeds, so stack unwinding unlocked the mutex.
  • std::make_unique puts the buffer on the heap. The std::unique_ptr deletes it when main returns, after the last line of output.
  • Handle deletes its copy operations. A copy would release the same resource twice.
JavaGitHub
public class Main {
    record Resource(String name, boolean failOnClose) implements AutoCloseable {
        Resource {
            System.out.println("open " + name);
        }

        @Override
        public void close() {
            System.out.println("close " + name);
            if (failOnClose) {
                throw new IllegalStateException("close failed: " + name);
            }
        }
    }

    public static void main(String[] args) {
        try (var source = new Resource("source", false);
                var target = new Resource("target", true)) {
            System.out.println("copy " + source.name() + " -> " + target.name());
            throw new IllegalArgumentException("disk full");
        } catch (IllegalArgumentException error) {
            System.out.println("caught: " + error.getMessage());
            for (Throwable suppressed : error.getSuppressed()) {
                System.out.println("suppressed: " + suppressed.getMessage());
            }
        }
    }
}
Output
open source
open target
copy source -> target
close target
close source
caught: disk full
suppressed: close failed: target
  • Verdict: native. try-with-resources closes every resource it declares, in the reverse order of declaration, whether the block completes or throws.
  • The resource type must implement AutoCloseable. A record can do this and keep its fields final.
  • The body throws first, then the close of target throws too. Java keeps the first exception and attaches the second with addSuppressed.
  • getSuppressed() returns the exceptions that were suppressed, so no error is lost.
#include <stdio.h>
#include <stdlib.h>

struct resource {
    const char *name;
};

static struct resource *open_resource(const char *name, int fail) {
    if (fail) {
        printf("open %s failed\n", name);
        return NULL;
    }
    struct resource *r = malloc(sizeof *r);
    if (r != NULL) {
        r->name = name;
        printf("open %s\n", name);
    }
    return r;
}

static void close_resource(struct resource *r) {
    printf("close %s\n", r->name);
    free(r);
}

// Returns 0 on success; every exit path goes through the labels below.
static int copy(int fail_target) {
    int status = -1;
    struct resource *target = NULL;
    struct resource *source = open_resource("source", 0);
    if (source == NULL) {
        goto out;
    }
    target = open_resource("target", fail_target);
    if (target == NULL) {
        goto close_source;
    }
    printf("copy %s -> %s\n", source->name, target->name);
    status = 0;
    close_resource(target);
close_source:
    close_resource(source);
out:
    return status;
}

int main(void) {
    printf("status %d\n", copy(0));
    printf("status %d\n", copy(1));
}
Output
open source
open target
copy source -> target
close target
close source
status 0
open source
open target failed
close source
status -1
  • Verdict: absent. C has no destructors and no statement that runs code on scope exit. Each release is a call that the programmer writes.
  • The goto cleanup idiom puts the releases at the end of the function, in reverse order of acquisition. A failure jumps to the label that releases only what was acquired.
  • target is declared at the top and set to NULL, so no goto jumps past its initialization.
  • GCC has __attribute__((cleanup(f))), which calls f when a local variable leaves scope. Clang accepts it too. It is an extension, not standard C.
Copy(fail: false);
try
{
    Copy(fail: true);
}
catch (IOException error)
{
    Console.WriteLine($"caught: {error.Message}");
}

using (var report = new Resource("report"))
{
    Console.WriteLine($"write {report.Name}");
}
Console.WriteLine("after using statement");

static void Copy(bool fail)
{
    using var source = new Resource("source");
    using var target = new Resource("target");
    if (fail)
    {
        throw new IOException("disk full");
    }
    Console.WriteLine($"copy {source.Name} -> {target.Name}");
}

sealed class Resource : IDisposable
{
    public string Name { get; }

    public Resource(string name)
    {
        Name = name;
        Console.WriteLine($"open {name}");
    }

    public void Dispose() => Console.WriteLine($"close {Name}");
}
Output
open source
open target
copy source -> target
close target
close source
open source
open target
close target
close source
caught: disk full
open report
write report
close report
after using statement
  • Verdict: native. A using declaration disposes its variable at the end of the enclosing scope, here the end of Copy.
  • Two using var declarations dispose in the reverse order of declaration: target, then source. The exception reaches the catch after both close.
  • The using statement with a block disposes at the end of that block. The output shows close report before after using statement.
  • Dispose comes from IDisposable. The class is sealed, so it needs no virtual Dispose(bool) method for subclasses.
JavaScriptGitHub
class Resource {
  constructor(name) {
    this.name = name;
    console.log("open", name);
  }

  [Symbol.dispose]() {
    console.log("close", this.name);
  }
}

function copy(fail) {
  using source = new Resource("source");
  using target = new Resource("target");
  if (fail) {
    throw new Error("disk full");
  }
  console.log("copy", source.name, "->", target.name);
}

copy(false);
try {
  copy(true);
} catch (error) {
  console.log("caught:", error.message);
}

{
  using stack = new DisposableStack();
  stack.defer(() => console.log("cleanup registered first"));
  stack.defer(() => console.log("cleanup registered second"));
  console.log("end of block");
}
Output
open source
open target
copy source -> target
close target
close source
open source
open target
close target
close source
caught: disk full
end of block
cleanup registered second
cleanup registered first
  • Verdict: native. A using declaration calls [Symbol.dispose]() on its value when the block exits, in the reverse order of declaration.
  • The exception from copy(true) reaches the catch after both resources close.
  • DisposableStack collects cleanup callbacks with defer and runs them in reverse order when the stack is disposed.
  • If both the block and a dispose method throw, the error is a SuppressedError that holds both. The await using form calls [Symbol.asyncDispose]().
TypeScriptGitHub
class Resource implements Disposable {
  readonly name: string;

  constructor(name: string) {
    this.name = name;
    console.log("open", name);
  }

  [Symbol.dispose](): void {
    console.log("close", this.name);
  }
}

function copy(fail: boolean): string {
  using source = new Resource("source");
  using target = new Resource("target");
  if (fail) {
    return "skipped";
  }
  return `copied ${source.name} -> ${target.name}`;
}

console.log(copy(false));
console.log(copy(true));
Output
open source
open target
close target
close source
copied source -> target
open source
open target
close target
close source
skipped
  • Verdict: native. TypeScript has the JavaScript using declaration and types it with the Disposable interface, which requires a [Symbol.dispose]() method.
  • The early return "skipped" still closes both resources before the caller prints the result.
  • The class assigns name in the constructor body. The type stripping of Node does not accept parameter properties such as constructor(readonly name: string).
package main

import (
	"errors"
	"fmt"
	"sync"
)

type resource struct{ name string }

func open(name string) *resource {
	fmt.Println("open", name)
	return &resource{name}
}

func (r *resource) Close() { fmt.Println("close", r.name) }

var (
	mu     sync.Mutex
	copies int
)

func copyFile(fail bool) (err error) {
	mu.Lock()
	defer mu.Unlock()
	source := open("source")
	defer source.Close()
	target := open("target")
	defer target.Close()
	if fail {
		return errors.New("disk full")
	}
	copies++
	return nil
}

func main() {
	fmt.Println("result:", copyFile(false))
	fmt.Println("result:", copyFile(true))
	fmt.Println("unlocked:", mu.TryLock(), "copies:", copies)
	mu.Unlock()
}
Output
open source
open target
close target
close source
result: <nil>
open source
open target
close target
close source
result: disk full
unlocked: true copies: 1
  • Verdict: native. defer saves a call that runs when the surrounding function returns, also when it returns an error or panics. Deferred calls run in reverse order.
  • defer mu.Unlock() right after mu.Lock() keeps the lock and its release together. Every return path of copyFile unlocks.
  • The scope of defer is the function, not the block. Put the body of a loop in its own function when each iteration opens a resource.
  • os.Exit ends the program without running deferred calls.
RustGitHub
use std::sync::Mutex;

struct Handle(&'static str);

impl Drop for Handle {
    fn drop(&mut self) {
        println!("release {}", self.0);
    }
}

struct Session {
    _socket: Handle,
    _buffer: Handle,
}

fn parse(input: &str) -> Result<u32, String> {
    let _log = Handle("log");
    let value = input.parse().map_err(|_| format!("not a number: {input}"))?;
    Ok(value)
}

fn main() {
    {
        let _first = Handle("first");
        let _second = Handle("second");
    }
    {
        let _session = Session {
            _socket: Handle("socket"),
            _buffer: Handle("buffer"),
        };
    }
    println!("{:?}", parse("x"));

    let early = Handle("early");
    drop(early);
    println!("after drop");

    let counter = Mutex::new(0);
    {
        let mut guard = counter.lock().unwrap();
        *guard += 1;
    }
    println!("unlocked after scope: {}", counter.try_lock().is_ok());
}
Output
release second
release first
release socket
release buffer
release log
Err("not a number: x")
release early
after drop
unlocked after scope: true
  • Verdict: native. The compiler drops each value at the end of its scope. Local variables drop in the reverse order of declaration.
  • The fields of Session drop in declaration order, so socket is released before buffer.
  • The ? operator returns early from parse, and _log is still dropped.
  • drop(early) ends a value before its scope does. The MutexGuard unlocks the mutex when its block ends, so try_lock succeeds.
BashGitHub
#!/usr/bin/env bash
set -eu

copy() (
  workdir=$(mktemp -d ./copy.XXXXXX)
  trap 'rm -rf "$workdir"; echo "removed workdir"' EXIT
  echo "made workdir"
  if [ "$1" = fail ]; then
    echo "copy failed" >&2
    exit 1
  fi
  echo "copied"
)

copy ok
copy fail 2>/dev/null || echo "copy returned $?"
leftover=$(find . -maxdepth 1 -name 'copy.*' | wc -l)
echo "workdirs left: $((leftover))"
Output
made workdir
copied
removed workdir
made workdir
removed workdir
copy returned 1
workdirs left: 0
  • Verdict: idiom. trap ... EXIT runs its commands when the shell exits. The exit builtin runs the EXIT trap before the shell ends.
  • The body of copy is a subshell ( ... ), so the trap belongs to the subshell and runs when the function returns.
  • The second call exits with status 1, and the trap still removes its directory. The last line shows that no work directory is left.
  • mktemp -d makes the directory before the trap is set. Set the trap at once after the acquisition, so no command runs between them.
  • Scope guards and defer. A scope guard is an object whose destructor runs an arbitrary function. Go defer and DisposableStack.defer in JavaScript are the same idea without an object type for each kind of resource.3236
  • Dynamic stacks of resources. contextlib.ExitStack and DisposableStack hold a list of release callbacks and run them in reverse order. They cover a number of resources that is known only at run time.2136
  • Ownership transfer. std::unique_ptr and a Rust value can move to another owner, and the scope of the last owner releases the resource. Statement-bound forms cannot do this: the block always releases.
  • Shared ownership. std::shared_ptr, Rc and Arc release the resource when the last owner dies. See Reference counting.
  • Lock guards. std::lock_guard and MutexGuard hold a lock for exactly one scope.1117 See Mutual exclusion.
  • try and finally. The manual form. It works in every language with exceptions, but each use of a resource repeats the release code. Stroustrup gives this as the reason C++ has no finally.1 See Exception.
  • Finalizers and cleaners. A finalizer runs when the collector frees an object, at a time the collector decides. The C# guide says that the programmer has no control over when the finalizer runs.29 Java deprecated finalization for removal, in part because no finalizer is guaranteed to run.26 Python does not guarantee __del__ for objects that live until the interpreter exits.20 Go does not guarantee that a function of runtime.AddCleanup runs before the program exits.34 So finalizers are a safety net, not RAII. The .NET dispose pattern uses both: Dispose releases at once, and GC.SuppressFinalize then cancels the finalizer.28 See Garbage collection, which shows a finalizer that runs late.

Pitfalls

A resource without a scope leaks on an early return

A release at the end of a function runs only when control reaches the end. Here the loop returns from the middle of the function, and the connection stays open.

This code runs but gives a wrong answer on purpose.

class Connection:
    open_count = 0

    def __init__(self, name):
        self.name = name
        Connection.open_count += 1

    def close(self):
        Connection.open_count -= 1

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, traceback):
        self.close()
        return False


def first_large(orders):
    conn = Connection("orders")
    for order in orders:
        if order > 100:
            return order  # conn.close() never runs
    conn.close()
    return None


first_large([5, 250, 7])
print("open connections:", Connection.open_count)
Output
open connections: 1

The same leak happens when an exception leaves the loop. The fix is to give the connection a scope, so that every exit closes it.

class Connection:
    open_count = 0

    def __init__(self, name):
        self.name = name
        Connection.open_count += 1

    def close(self):
        Connection.open_count -= 1

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, traceback):
        self.close()
        return False


def first_large(orders):
    with Connection("orders"):
        for order in orders:
            if order > 100:
                return order
    return None


first_large([5, 250, 7])
print("open connections:", Connection.open_count)
Output
open connections: 0

Go defer in a loop runs at the end of the function

A deferred call runs when the surrounding function returns, not when the loop body ends.32 A loop that opens a file and defers its close keeps every file open until the loop is over.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type file struct{ name string }

var openFiles int

func openFile(name string) *file {
	openFiles++
	return &file{name}
}

func (f *file) Close() { openFiles-- }

func processAll(names []string) {
	for _, name := range names {
		f := openFile(name)
		defer f.Close()
		fmt.Println("processing", f.name, "open files:", openFiles)
	}
}

func main() {
	processAll([]string{"a.log", "b.log", "c.log"})
	fmt.Println("after return, open files:", openFiles)
}
Output
processing a.log open files: 1
processing b.log open files: 2
processing c.log open files: 3
after return, open files: 0

With many names, the program can run out of file descriptors. Move the body into a function of its own, so that each iteration has a function scope.

package main

import "fmt"

type file struct{ name string }

var openFiles int

func openFile(name string) *file {
	openFiles++
	return &file{name}
}

func (f *file) Close() { openFiles-- }

func processOne(name string) {
	f := openFile(name)
	defer f.Close()
	fmt.Println("processing", f.name, "open files:", openFiles)
}

func main() {
	for _, name := range []string{"a.log", "b.log", "c.log"} {
		processOne(name)
	}
	fmt.Println("after loop, open files:", openFiles)
}
Output
processing a.log open files: 1
processing b.log open files: 1
processing c.log open files: 1
after loop, open files: 0

A C++ destructor that throws ends the program

A destructor without a noexcept specifier is non-throwing.8 When an exception reaches the outermost block of a non-throwing function, the program calls std::terminate.89 Here the destructor calls a function that throws, and the catch clause never runs.

This code fails on purpose. The output below is the error.

#include <print>
#include <stdexcept>

void flush_log(bool fail) {
    if (fail) {
        throw std::runtime_error("flush failed");
    }
}

struct Log {
    bool fail;
    ~Log() { flush_log(fail); }
};

int main() {
    try {
        Log log{true};
        std::println("writing");
    } catch (const std::exception& error) {
        std::println("caught {}", error.what());
    }
}

Marking the destructor noexcept(false) does not help much: if the destructor throws during stack unwinding, the program still terminates.9 Give the class a close method that may throw, and let the destructor release without throwing if the caller did not close. The destructor of std::basic_filebuf does this: it calls close() and catches any exception.13

#include <print>
#include <stdexcept>

void flush_log(bool fail) {
    if (fail) {
        throw std::runtime_error("flush failed");
    }
}

struct Log {
    bool fail;
    bool closed = false;

    void close() {
        closed = true;
        flush_log(fail);
    }

    ~Log() {
        if (!closed) {
            try {
                flush_log(fail);
            } catch (...) {
                // A destructor must not throw; the caller can call close() to see the error.
            }
        }
    }
};

int main() {
    try {
        Log log{true};
        std::println("writing");
        log.close();
    } catch (const std::exception& error) {
        std::println("caught {}", error.what());
    }
}
Output
writing
caught flush failed

A C++ temporary dies at the end of its statement

A temporary object is destroyed as the last step of the full-expression that made it.10 A guard without a name is a temporary, so it acquires and releases in the same statement, and the code after it runs unprotected.

This code runs but gives a wrong answer on purpose.

#include <print>

struct Guard {
    Guard() { std::println("lock"); }
    ~Guard() { std::println("unlock"); }
};

int main() {
    Guard{};
    std::println("update the shared counter");
}
Output
lock
unlock
update the shared counter

Give the guard a name, so that it lives to the end of the block. With the Clang and libc++ that recorded these examples, std::lock_guard<std::mutex>{m}; does not compile under -Werror, because the constructor is marked nodiscard. std::lock_guard<std::mutex>(m); declares a variable named m instead, and fails too. A guard type of your own gets no such check.

#include <print>

struct Guard {
    Guard() { std::println("lock"); }
    ~Guard() { std::println("unlock"); }
};

int main() {
    Guard guard;
    std::println("update the shared counter");
}
Output
lock
update the shared counter
unlock

Rust does not guarantee that Drop runs

std::mem::forget takes a value and never runs its destructor. It is safe code, because the safety rules of Rust do not include a promise that destructors run. A cycle of Rc values has the same effect.1614 Here a forgotten MutexGuard leaves the mutex locked.

This code runs but gives a wrong answer on purpose.

use std::sync::Mutex;

fn main() {
    let orders = Mutex::new(Vec::new());
    let mut guard = orders.lock().unwrap();
    guard.push(1);
    std::mem::forget(guard);
    println!("lock free again: {}", orders.try_lock().is_ok());
}
Output
lock free again: false

Unsafe code must not depend on a destructor for soundness, for the same reason.14 To end a guard early, pass it to drop.

use std::sync::Mutex;

fn main() {
    let orders = Mutex::new(Vec::new());
    let mut guard = orders.lock().unwrap();
    guard.push(1);
    drop(guard);
    println!("lock free again: {}", orders.try_lock().is_ok());
}
Output
lock free again: true

Python binds the result of __enter__, not the manager

The as target of a with statement gets the return value of __enter__.1819 A manager whose __enter__ has no return gives None.

This code raises AttributeError, on purpose.

class Ledger:
    def __init__(self):
        self.entries = []

    def __enter__(self):
        print("lock ledger")

    def __exit__(self, exc_type, exc, traceback):
        print("unlock ledger")
        return False

    def add(self, amount):
        self.entries.append(amount)


with Ledger() as ledger:
    ledger.add(10)

Return self from __enter__ when the target should be the manager. Some managers return another object on purpose: a threading.Lock gives the result of acquire.

import threading


class Ledger:
    def __init__(self):
        self.entries = []

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, traceback):
        return False

    def add(self, amount):
        self.entries.append(amount)


with Ledger() as ledger:
    ledger.add(10)
print("entries:", ledger.entries)

with threading.Lock() as held:
    print("target of a lock:", held)
Output
entries: [10]
target of a lock: True

Cost

  • Destructor calls. A destructor is an ordinary function that the compiler calls at each exit of the scope. The standard defines when and in which order, not how.45 The destructor of std::unique_ptr is one test and one call of the deleter.12
  • Statement forms. A with, using or try-with-resources block costs about what the equivalent try and finally costs. Python looks up and calls two methods per block.18 Java adds a null check per resource and the bookkeeping for suppressed exceptions.23
  • Go defer. Each execution of defer evaluates and saves the function value and its arguments.32 In a loop, this storage grows with the number of iterations until the function returns.
  • Finalizers. A finalizer is not free even when it does nothing. In .NET, an object with a finalizer gets an entry in the Finalize queue, and an empty finalizer still costs performance.29 The dispose pattern calls GC.SuppressFinalize after Dispose, so the collector no longer needs to run the finalizer.28 JEP 421 lists the costs of finalization for the JDK and for every program.26

History

  • 1980. Destructors were among the first features of C with Classes. Stroustrup writes that resource management motivated them: constructors acquire resources, and destructors release them.3
  • 1990. Andrew Koenig and Stroustrup presented exception handling for C++ at the USENIX C++ Conference in April 1990. Stroustrup writes that this paper and the exception design of the ARM waited about half a year. He held them back until he had found "resource acquisition is initialization".3
  • 2001. The first edition of ECMA-334, the C# specification, defined the using statement on System.IDisposable.31
  • 2005. PEP 343 proposed the with statement for Python 2.5.22
  • 2011. JSR 334, the small language changes for Java SE 7, reached its final release on 20 July 2011. It included the try-with-resources statement.25
  • 2019. C# 8.0 added the using declaration.30
  • 2021. JEP 421, created in September 2021, deprecated finalization for removal and named try-with-resources and cleaners as the replacement. It was delivered in JDK 18.26
  • Stage 4. The Explicit Resource Management proposal for JavaScript is on the TC39 list of finished proposals. The list gives 2027 as its expected year of publication in ECMA-262.37

References

  1. Bjarne Stroustrup, C++ Style and Technique FAQ, Why doesn't C++ provide a "finally" construct?
  2. Bjarne Stroustrup, C++ Glossary, resource acquisition is initialization; RAII; resource; resource leak
  3. Bjarne Stroustrup, Evolving a language in and for the real world, C++ 1991-2006, HOPL III, 2007, section 5.3.1 Resource management
  4. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [class.dtor] paragraphs 6, 13 and 14
  5. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [stmt.dcl] paragraph 2
  6. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [stmt.jump] paragraph 2
  7. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.ctor] paragraphs 1 to 3, stack unwinding
  8. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.spec] paragraphs 3 and 5
  9. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [except.terminate] paragraph 1, items 1.3 and 1.4
  10. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [class.temporary] paragraph 4
  11. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.guard] paragraphs 1, 2 and 6
  12. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [unique.ptr.single.dtor] paragraph 1
  13. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [filebuf.cons] paragraph 5, the destructor of basic_filebuf
  14. The Rust Reference, Destructors, destructors.intro, destructors.operation, destructors.scope.intro, destructors.scope.bindings.let, destructors.manually-suppressing, destructors.process-termination
  15. The Rust Programming Language, 15.3 Running Code on Cleanup with the Drop Trait, Dropping a Value Early with std::mem::drop (error E0040)
  16. The Rust Standard Library, function std::mem::forget, Safety
  17. The Rust Standard Library, struct std::sync::MutexGuard, struct description
  18. The Python Language Reference, Compound statements, Python 3.14, 8.5 The with statement
  19. The Python Language Reference, Data model, Python 3.14, 3.3.9 With Statement Context Managers, object.__enter__ and object.__exit__
  20. The Python Language Reference, Data model, Python 3.14, Basic customization, object.__del__
  21. The Python Standard Library, contextlib, Python 3.14, class contextlib.ExitStack
  22. PEP 343: The "with" Statement, header (Created 13-May-2005, Python-Version 2.5)
  23. The Java Language Specification, Java SE 25 Edition, 14.20.3 try-with-resources and 14.20.3.1 Basic try-with-resources
  24. Java SE 25 API, java.lang.AutoCloseable, interface description and close()
  25. JSR 334: Small Enhancements to the Java Programming Language, stage timeline (Final Release 20 Jul 2011) and section 2.1 and 2.3
  26. JEP 421: Deprecate Finalization for Removal, Summary; Motivation, Finalization and its flaws
  27. C# language reference, using statement, the using statement and the using declaration
  28. .NET documentation, Implement a Dispose method, the dispose pattern; Dispose should be idempotent; GC.SuppressFinalize
  29. C# programming guide, Finalizers, Remarks, the notes on the Finalize queue and on application termination
  30. C# language version history, C# version 8.0, Using declarations
  31. ECMA-334, C# Language Specification, 1st edition, December 2001, 15.13 The using statement
  32. The Go Programming Language Specification, Defer statements
  33. Go standard library, package os, func Exit
  34. Go standard library, package runtime, func AddCleanup, func SetFinalizer
  35. Kotlin standard library, kotlin.io, use, inline fun <T : Closeable?, R> T.use(block: (T) -> R): R
  36. ECMAScript Explicit Resource Management, proposal README, Syntax, using declarations; Semantics, the reverse order of disposal and SuppressedError; DisposableStack
  37. TC39, Finished Proposals, the row Explicit Resource Management, Expected Publication Year
  38. bash(1), the Bash manual page, from the upstream Git repository of Bash, SHELL BUILTIN COMMANDS, trap and exit
  39. Using the GNU Compiler Collection, Common Variable Attributes, cleanup (cleanup_function)
  40. PowerShell documentation, about_Functions_Advanced_Methods, clean

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/9AX66E/text.yaml