Modern C++ and C Alternatives

RAII in C++ - Automatic Cleanup vs goto cleanup in C

Never forget to close a file again. RAII ties a resource to an object so cleanup runs on every exit path, even exceptions.

  • Advanced
  • 3 min read
  • 2 runnable examples
What you'll learn
  • Constructors acquire, destructors release
  • Why early returns leak in C
  • RAII types: fstream, unique_ptr, lock_guard
{ std::ofstream out("data.txt"); ... }
  1. 1std::ofstream out(...)Constructor opens the file
  2. 2out << dataUse it
  3. 3return / throw / }Leave the scope any way
  4. 4~ofstream()Destructor closes the file

Resource lifetime equals object lifetime

The problem

Files, memory and locks must be released when you are done, on every path: normal end, early return, or error. Forgetting one path leaks the resource. C++ ties the release to an object, so it happens automatically.

Think of it like this

RAII is like a hotel key card that automatically stops working when you check out. You never have to remember to hand it in; leaving the hotel (the scope) ends the access, whatever route you take out.

From a hotel key card to code
fopen("scores.txt", "w")🗝️ C: get a key you must return yourself
goto cleanup;🚪 C: every exit must pass the front desk
std::ofstream file("scores.txt");💳 C++: a card tied to your stay
end of main🏁 Leaving the scope closes the file automatically
The resource lives exactly as long as the object.
In one sentence

RAII (Resource Acquisition Is Initialization) means an object acquires a resource in its constructor and releases it in its destructor. Cleanup then happens automatically when the object goes out of scope.

Important points

  1. In C, every failure jumps to cleanup, where fclose runs if file was opened.
  2. result starts as 1 (failure) and becomes 0 only after fputs succeeds.
  3. In C++, std::ofstream opens the file in its constructor.
  4. The file closes automatically when file goes out of scope at the end of main.

When to use it

  • Files, sockets and database connections.
  • Memory with std::unique_ptr and containers.
  • Locks with std::lock_guard, so a mutex is always released.

When not to use it

  • C code: there are no destructors, so use a single cleanup path instead.
  • Resources that must outlive the scope: move ownership to an object that lives longer.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int main(void) {
    int result = 1;
    FILE *file = fopen("scores.txt", "w");
    if (!file) goto cleanup;
    if (fputs("Ada 95\n", file) < 0) goto cleanup;
    result = 0;

cleanup:
    if (file) fclose(file);
    puts(result ? "failed" : "saved");
    return result;
}
Get a Run button for this example Result of running the code
saved
C++
Run code →
main.cpp
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("scores.txt");
    if (!file) return 1;
    file << "Ada 95\n";
    std::cout << "saved\n";
}
Get a Run button for this example Result of running the code
saved

C and C++ comparison

The C version jumps to one cleanup label from every failure, so fclose runs on all paths and result reports success or failure. In C++, std::ofstream opens the file when it is created and closes it in its destructor. Leaving main by any path closes the file without extra code.

C

C uses naming conventions, callbacks, macros, and explicit context structures.

C++

Language features provide scoped, type-safe, and often zero-overhead abstractions.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Write the C mechanism before the C++ abstraction.
  • Remove manual cleanup with RAII.
  • Check whether the abstraction adds allocations or virtual dispatch.

Common mistakes

Missing cleanup on an early return

Returning before fclose leaks the file handle.

Problem
if (fputs("Ada 95\n", file) < 0) return 1;
Fix
if (fputs("Ada 95\n", file) < 0) goto cleanup;

Manual new and delete in C++

An exception between them leaks the memory.

Problem
int *data = new int[100];
// ...
delete[] data;
Fix
std::vector<int> data(100);

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges