RAII (Resource Acquisition Is Initialization)
Use case
Automatically release a lock on shared disassembler cache when leaving scope.
Explanation
RAII ties resource lifetime to object lifetime. Constructor acquires, destructor releases. Guarantees cleanup even on exceptions.
Code
#include <cstdint>
#include <mutex>
#include <print>
std::mutex g_cache_mutex;
class CacheLock {
public:
CacheLock(std::mutex &m) : mutex_(m) {
mutex_.lock();
std::println("Cache locked.");
}
~CacheLock() {
mutex_.unlock();
std::println("Cache unlocked.");
}
private:
std::mutex &mutex_;
};
void disassemble(uint64_t addr) {
CacheLock lock(g_cache_mutex);
std::println("Disassembling {:#x}...", addr);
}
int main() {
disassemble(0x10001000);
disassemble(0x10002000);
return 0;
}
Output
$ ./src/design-patterns-and-idioms/build/raii
Cache locked.
Disassembling 0x10001000...
Cache unlocked.
Cache locked.
Disassembling 0x10002000...
Cache unlocked.