0Pricing
C++ Academy · Lesson

Scope Guards

Run cleanup on scope exit.

Scope Guards is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is a Scope Guard?

A scope guard is an RAII object whose only job is to run a cleanup action when it goes out of scope — even on early return or exception.

The Problem It Solves

Without a guard, cleanup after an early return or a throw is easy to forget. A scope guard makes the action automatic.

lock_guard: A Standard Scope Guard

std::lock_guard locks a mutex on construction and unlocks it on destruction — a built-in scope guard for locks.

#include <mutex>

std::mutex m;

void critical() {
    std::lock_guard<std::mutex> lk(m);   // locked
    // ... work ...
}                                        // unlocked automatically

A Hand-Rolled Guard

You can write a guard that holds a function and calls it in the destructor.

#include <iostream>
#include <functional>

class ScopeGuard {
    std::function<void()> fn;
public:
    ScopeGuard(std::function<void()> f) : fn(std::move(f)) {}
    ~ScopeGuard() { fn(); }
};

int main() {
    ScopeGuard g([] { std::cout << "cleanup\n"; });
    std::cout << "work\n";
}

Cleanup Runs on Early Return

Because the destructor fires at scope exit, the guard's action runs no matter how the function leaves.

#include <iostream>
#include <functional>

class ScopeGuard {
    std::function<void()> fn;
public:
    ScopeGuard(std::function<void()> f) : fn(std::move(f)) {}
    ~ScopeGuard() { fn(); }
};

void run(bool stop) {
    ScopeGuard g([] { std::cout << "always cleaned\n"; });
    if (stop) return;
}

int main() { run(true); }

Cleanup Runs on Exception

If an exception unwinds through the scope, the guard's destructor still runs, releasing the resource safely.

Cancelling a Guard

Sometimes you want to skip cleanup (the operation succeeded). Real guards offer a dismiss() to disable the action.

#include <iostream>
#include <functional>

class ScopeGuard {
    std::function<void()> fn;
    bool active = true;
public:
    ScopeGuard(std::function<void()> f) : fn(std::move(f)) {}
    void dismiss() { active = false; }
    ~ScopeGuard() { if (active) fn(); }
};

int main() {
    ScopeGuard g([] { std::cout << "rollback\n"; });
    g.dismiss();   // success: no rollback
}

Use for Rollback

Scope guards shine for transactional code: register a rollback action, do the work, then dismiss the guard on success.

Guards Are Move-Only

A guard should not be copied — copying would run the action twice. Make guards move-only or non-copyable.

Standard and Library Helpers

std::scoped_lock guards multiple mutexes, and libraries like GSL provide finally. Many codebases ship a small ScopeGuard utility.

Prefer Specific RAII Types

When a dedicated RAII type exists (lock_guard, unique_ptr, fstream), prefer it. Use a generic scope guard only for ad-hoc cleanup with no natural wrapper.

Quick Check

Test your understanding of scope guards.

Recap

You learned that a scope guard runs cleanup automatically at scope exit via RAII. It handles early returns and exceptions, supports rollback with a dismiss(), and should be move-only. Prefer dedicated RAII types when they exist.

Frequently asked questions

Is the “Scope Guards” lesson free?

Yes — the full text of “Scope Guards” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “Scope Guards”?

Run cleanup on scope exit. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Scope Guards” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The RAII Principle
  2. Destructors and Cleanup
  3. Rule of Three/Five
  4. Scope Guards
← Back to C++ Academy