Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Concurrency and Memory

scope Guards, RAII and Manual Memory in D

Manage resources deterministically in D: scope(exit/success/failure), struct destructors for RAII, malloc and free, std.experimental.allocator and arenas, with a C cleanup stand-in.

The garbage collector frees memory, but not files, sockets, locks or database connections: those must be released at a known moment. D gives you three tools for deterministic cleanup: scope guards, struct destructors (RAII), and, when you want it, manual or arena allocation. This lesson covers all three.

D code is read-only on this site. The runnable stand-ins use C: a GCC cleanup attribute that mimics scope(exit), a defer-style stack, and a bump allocator (arena).

scope(exit), scope(success), scope(failure)

A scope statement schedules code to run when the current block ends. Guards run in reverse order, so you write the cleanup right next to the acquisition:

D
void process(string path)
{
    auto f = File(path, "r");
    scope(exit) f.close();                       // always runs

    auto lock = acquire();
    scope(exit) release(lock);

    scope(failure) writeln("processing failed");  // only if an exception left the block
    scope(success) writeln("processing OK");      // only on a normal exit

    doWork(f);
}
  • scope(exit) runs on normal exit, early return, break, or an exception.
  • scope(success) runs only if the block ends without throwing.
  • scope(failure) runs only if it ends by throwing.

This replaces try/finally pyramids and goto-style cleanup labels. Because the guard sits beside the thing it protects, forgetting a cleanup path is much harder.

The GCC attribute __attribute__((cleanup(fn))) in C runs a function when a variable leaves scope, in reverse declaration order, exactly like stacked scope(exit) statements.

C Stand-in: scope(exit) with the cleanup attribute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Both runs release the lock first and then close the file, whichever way the function returns.

RAII with structs

A struct destructor ~this() runs deterministically when the value goes out of scope (or is overwritten). Structs are values, so there is no waiting for the GC. That is the C++-style RAII idiom.

D
struct Handle
{
    private int fd = -1;

    this(string path) { fd = open(path); }
    ~this() { if (fd >= 0) close(fd); }

    @disable this(this);        // forbid copying: one owner only
}

void main()
{
    auto h = Handle("data.bin");
    // ... use h ...
}   // ~this() runs here

Use @disable this(this) to forbid copies when a copy would mean double release, or write a postblit/copy constructor that duplicates the resource. Phobos types such as File and RefCounted!T use these techniques. std.typecons.scoped!MyClass() even puts a class instance on the stack so its destructor runs at scope end.

Manual allocation

Sometimes you want no GC: embedded code, a library with strict latency, or memory shared with C. The basics:

D
import core.stdc.stdlib : malloc, free;

int* p = cast(int*) malloc(100 * int.sizeof);
scope(exit) free(p);
p[0 .. 100] = 0;             // slice the pointer to use it safely

Never point GC-managed objects from such memory without telling the collector (GC.addRange). Prefer std.experimental.allocator, whose allocators (Mallocator, FreeList, Region, StatsCollector) compose and share one API: make!T, makeArray!T(n), dispose(x).

Arenas: free everything at once

An arena (region) hands out memory by bumping a pointer and frees it all in one step. It is ideal for a request, a frame, or a compile pass: many small allocations, one lifetime, no individual free.

C Stand-in: a bump allocator (arena)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Choosing a strategy

Situation Choice
General application code GC, plus scope(exit) for files and locks
Owns a resource, copying is meaningless struct with ~this() and @disable this(this)
Many short-lived objects with one lifetime arena / Region allocator
Hot path with no allocation allowed @nogc, stack arrays, preallocated buffers
Interop with C libraries malloc/free, Mallocator, GC.addRange where needed

Common mistakes

  • Relying on a class destructor to close a file: it may never run before exit.
  • Freeing memory and keeping a slice into it (use-after-free). Slices do not own memory.
  • Forgetting scope(exit) after malloc when a later line can throw.
  • Copying a struct that owns a resource without disabling or defining the copy.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what order do multiple scope(exit) statements run?

    Like a stack: the most recently registered guard runs first.
  2. 2. Which guard runs only when an exception leaves the block?

    scope(failure) is for rollback or logging when something throws.
  3. 3. Why use a struct destructor rather than a class destructor to close a file?

    Class destructors run at GC time, which may be late or never.
  4. 4. What is the main benefit of an arena allocator?

    Arenas trade fine-grained freeing for speed and simplicity.

Summary

  • scope(exit/success/failure) place cleanup beside acquisition and run in reverse order.
  • Struct destructors give C++-style RAII; disable or define copying when a resource is owned.
  • malloc/free, std.experimental.allocator and arenas serve GC-free needs.
  • Do not use class destructors for time-critical cleanup.

Next: dub and Modules