RAII is a C++ programming idiom where resources (like memory, file handles, locks, sockets) are tied to the lifetime of objects.
The resource is:
So when an object goes out of scope, its destructor is automatically called, releasing the resource.
| Use Case | Description |
|---|---|
| Memory management | std::unique_ptr, std::shared_ptr use RAII |
| File management | std::ifstream, std::ofstream automatically close files |
| Mutexes / Locks | std::lock_guard, std::unique_lock unlock automatically |
| Network sockets | Automatically close sockets when the object goes out of scope |
| Database connections | RAII wrapper ensures proper disconnection |