Junior — Middle
Can you give examples of resources managed using RAII, besides smart pointers?
sobes.tech AI
Answer from AI
RAII (Resource Acquisition Is Initialization) is an idiom in C++ that ties the lifetime of a resource to the lifetime of an object.
Besides smart pointers, RAII is often used to manage:
- File descriptors: a class opens a file in its constructor and closes it in its destructor.
- Mutexes and locks: an object locks a resource upon creation and unlocks it upon destruction, for example,
std::lock_guard. - Network connections: opening a connection in the constructor and closing it in the destructor.
- Manually allocated memory: wrappers for dynamic memory allocation and deallocation.
Example with mutex locking:
std::mutex mtx;
void func() {
std::lock_guard<std::mutex> lock(mtx); // locks the mutex
// critical section
} // upon exiting the function, lock_guard is destroyed and the mutex is unlocked
This approach guarantees resource release even in case of exceptions.