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 exit
m.lock();
if (err)
return; // <-- leaks the lock!
m.unlock();

What this lesson walks through

  1. 01RAII: acquire in ctor, release in dtor
  2. 02Entering scope locks the mutex
  3. 03Critical section runs
  4. 04Scope exit unlocks automatically
  5. 05Exceptions? Still released.
  6. 06Manual lock/unlock: the leak
  7. 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.

← Previous
shared_ptr Cycles & weak_ptr
Next →
Lambda Captures: [=] vs [&]