Scope Guards
Run cleanup on scope exit.
Scope Guards is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.
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 automaticallyA 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.
Learn C++ with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Scope Guards” lesson free?
Yes — any 3 lessons of the C++ Academy learning path, including “Scope Guards”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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.