What is RAII in C++?
RAII in C++ ties resource lifetime to object lifetime — acquire in the constructor, release in the destructor — for automatic, exception-safe cleanup.
Expected Interview Answer
RAII (Resource Acquisition Is Initialization) is a C++ idiom where a resource's lifetime is tied to an object's lifetime: the resource is acquired in the constructor and released in the destructor, so cleanup is automatic and exception-safe.
Because C++ guarantees that a stack object's destructor runs when it goes out of scope — including during stack unwinding from an exception — wrapping resources like heap memory, file handles, locks, or sockets in an object ensures they are always released exactly once. Standard examples include std::unique_ptr, std::lock_guard, and std::fstream. RAII eliminates manual paired new/delete or lock/unlock, preventing leaks and double-frees even when errors occur.
- Automatic, deterministic resource cleanup
- Exception safety via stack unwinding
- No manual paired acquire/release calls to forget
- Prevents leaks, double-frees, and unreleased locks
- Encapsulates resource logic in one reusable type
AI Mentor Explanation
RAII is like a groundsman assigned the pitch covers the moment rain threatens: the instant his shift object is created he rolls the covers on, and the moment his shift ends he must roll them off. Cleanup is bound to his shift, so the pitch is never left exposed even if play stops abruptly.
Step-by-Step Explanation
Step 1
Acquire in the constructor
Obtain the resource (allocate memory, open a file, lock a mutex) as part of constructing the wrapper object.
Step 2
Own the resource
The object holds the resource handle for the duration of its lifetime and exposes safe access to it.
Step 3
Release in the destructor
Free the resource in the destructor so it is released automatically when the object goes out of scope.
Step 4
Rely on stack unwinding
Because destructors run during exception unwinding, resources are released even when an exception is thrown.
Step 5
Manage ownership correctly
Delete or define copy/move semantics (Rule of Five) so ownership is never duplicated or lost, avoiding double-free.
What Interviewer Expects
- Resource lifetime tied to object lifetime
- Constructor acquires, destructor releases
- Exception safety through stack unwinding
- Concrete examples: unique_ptr, lock_guard, fstream
- Awareness of the Rule of Three/Five and ownership
Common Mistakes
- Thinking RAII is only about heap memory, not files, locks, or sockets
- Forgetting that destructors run during exception unwinding
- Allowing accidental copies that cause double-free
- Manually calling new/delete inside RAII-managed code
- Not following the Rule of Five when a class owns a resource
Best Answer (HR Friendly)
“RAII is a C++ technique where an object grabs a resource when it is created and releases it when it is destroyed. This means memory, files, and locks get cleaned up automatically as soon as they are no longer needed, even if something goes wrong.”
Code Example
#include <iostream>
#include <memory>
#include <mutex>
class FileHandle {
std::FILE* f;
public:
explicit FileHandle(const char* path)
: f(std::fopen(path, "r")) {} // acquire in constructor
~FileHandle() { if (f) std::fclose(f); } // release in destructor
FileHandle(const FileHandle&) = delete; // no copies -> no double-free
FileHandle& operator=(const FileHandle&) = delete;
std::FILE* get() const { return f; }
};
std::mutex m;
void work() {
std::lock_guard<std::mutex> lock(m); // unlocks on scope exit
auto buf = std::make_unique<int[]>(1024); // frees automatically
FileHandle fh("data.txt"); // closes automatically
// even if an exception is thrown here, all three are cleaned up
}Follow-up Questions
- How does RAII provide exception safety?
- What is the Rule of Three, Five, and Zero?
- How do unique_ptr and shared_ptr differ in ownership?
- Why should RAII classes usually disable or define copy semantics?
- How does std::lock_guard use RAII to manage a mutex?
MCQ Practice
1. In RAII, when is a resource released?
RAII ties the resource to object lifetime, so the destructor releases it when the object goes out of scope.
2. Why does RAII give exception safety?
When an exception propagates, C++ unwinds the stack and runs destructors of local objects, releasing their resources.
3. Which standard type is a classic example of RAII for mutexes?
std::lock_guard locks a mutex in its constructor and unlocks it in its destructor, a textbook RAII use.
Flash Cards
What does RAII stand for? — Resource Acquisition Is Initialization — bind a resource's lifetime to an object's lifetime.
Where is the resource acquired and released? — Acquired in the constructor, released in the destructor.
Why is RAII exception-safe? — Destructors run during stack unwinding, so resources are released even when an exception is thrown.
Three standard RAII examples? — std::unique_ptr (memory), std::lock_guard (mutex), std::fstream (file handle).