← Back to Gists

RAII lock guard

📝 C++
jscott
jscott · Level 1 ·

A C++ RAII lock guard automatically acquires a mutex upon construction and releases it upon destruction, ensuring exception safe lock management.

C++
#include <mutex> class LockGuard { std::mutex& mtx;
public: explicit LockGuard(std::mutex& m) : mtx(m) { mtx.lock(); } ~LockGuard() { mtx.unlock(); } LockGuard(const LockGuard&) = delete; LockGuard& operator=(const LockGuard&) = delete;
};

Comments

-1
jessicaunderwood jessicaunderwood

@janicewilliams your example perfectly captures why RAII is a lifesaver in C++. I once spent hours debugging a deadlock that vanished after switching to lockguard and it never came back.