What is RAII in C++?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex C++ topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
RAII (Resource Acquisition Is Initialization) is the most fundamental C++ idiom. The idea: tie the lifetime of a resource (memory, file handles, mutex locks, network connections) to the lifetime of an object — acquire in the constructor, release in the destructor. Since C++ guarantees destructors run when objects go out of scope (even during exceptions), resources are always properly released. Classic problem without RAII: void badFunction() { FILE* f = fopen("data.txt", "r"); processFile(f); // What if this throws? fclose(f); // May never run -- RESOURCE LEAK! }. RAII solution (std::fstream): void goodFunction() { std::ifstream f("data.txt"); processFile(f); // f.close() called automatically on scope exit, even if exception! }. Custom RAII class: class FileGuard { FILE* file; public: FileGuard(const char* path, const char* mode) : file(fopen(path, mode)) { if (!file) throw std::runtime_error("Can't open file"); } ~FileGuard() { if (file) fclose(file); } // Destructor releases // Non-copyable (owns unique resource): FileGuard(const FileGuard&) = delete; FileGuard& operator=(const FileGuard&) = delete; FILE* get() const { return file; } };. RAII in the standard library: std::unique_ptr/std::shared_ptr (memory), std::lock_guard/std::unique_lock (mutex), std::fstream (files), std::vector/std::string (memory). Why RAII matters: exception safety — resources released even when exceptions propagate; correct behavior in all code paths without try/finally; no need for garbage collection — deterministic destruction.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a C++ codebase.