cpp core · high
RAII & lock_guard
Why scope-bound release (lock_guard) beats manual lock/unlock: the destructor frees the resource on every exit path, including exceptions.
🔑 Key line
RAII binds resource lifetime to scope: the destructor releases on every exit (return, break, exception). lock_guard locks in ctor, unlocks in dtor.
The code
// RAII: lock_guard{ std::lock_guard<std::mutex> lk(m); // ctor: m.lock() doWork(); // may throw} // dtor: m.unlock() - always
// Manual (BUG): unlock skipped on early exitm.lock();if (err) return; // <-- leaks the lock!m.unlock();What this lesson walks through
- 01RAII: acquire in ctor, release in dtor
- 02Entering scope locks the mutex
- 03Critical section runs
- 04Scope exit unlocks automatically
- 05Exceptions? Still released.
- 06Manual lock/unlock: the leak
- 07Why RAII wins
RAII binds a resource to an object's lifetime: the constructor acquires it, the destructor releases it. std::lock_guard is the canonical example for a mutex.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of RAII & lock_guard and 100+ animated C++ interview lessons.