Learn C++
#include "advanced/raii.hpp"

RAII: Resource Management in C++

//concept

RAII (Resource Acquisition Is Initialization) ties every resource's lifetime to an object's: the constructor acquires, the destructor releases, and C++'s deterministic destruction guarantees release at scope exit — including during exception unwinding. Files, locks, memory, and handles managed this way simply cannot leak through forgotten cleanup.

This single idiom is why modern C++ rarely writes explicit cleanup: lock_guard unlocks mutexes, fstream closes files, unique_ptr frees memory, all by falling out of scope. Designing a class? Acquire in constructors, release in the destructor, and every use becomes automatically safe.

//how it works
1

Acquire in constructors

Open the file, lock the mutex, allocate the buffer — a constructed object means a held resource, by construction.

2

Release in destructors

The destructor mirrors every acquisition — scope exit (normal or exceptional) triggers deterministic release.

3

Exception-safe by construction

Unwinding destroys locals in order, so RAII guards clean up error paths no human remembered to write.

4

Compose, don't clean

Members destruct automatically after the body — classes of RAII members need no handwritten cleanup at all.

//example
#include <iostream>
#include <fstream>
#include <string>
 
int main() {
{
std::ofstream log("app.log");
log << "started" << std::endl;
}
std::ifstream in("app.log");
std::string line;
std::getline(in, line);
std::cout << line << std::endl;
return 0;
}
Output
started
1The ofstream acquires app.log on construction and writes one line.
2Leaving the inner scope destroys log, flushing and closing the file with no explicit call.
3The ifstream (itself RAII) reopens and reads the line back for printing.
//use cases
Mutex locking via lock_guard that can't forget to unlock
File and socket handles that close themselves at scope exit
Exception-safe functions with zero explicit cleanup code
Designing owners whose destructor is the entire deallocation strategy

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.