RAII Pattern

Resource Acquisition Is Initialization

Interview Relevant: Key C++ idiom

RAII Pattern

Tie resource lifetime to object lifetime.

Code Examples

RAII for exception-safe resource management.

cpp
1// RAII File Handle
2class FileHandle {
3    FILE* file;
4public:
5    FileHandle(const char* name) : file(fopen(name, "r")) {
6        if (!file) throw runtime_error("Can't open file");
7    }
8    ~FileHandle() {
9        if (file) fclose(file);
10    }
11    // Delete copy to prevent double-free
12    FileHandle(const FileHandle&) = delete;
13    FileHandle& operator=(const FileHandle&) = delete;
14};
15
16// Usage - file always closed, even with exceptions
17void process() {
18    FileHandle fh("data.txt");
19    // Use file...
20}  // fclose called automatically
21
22// RAII lock guard
23void threadSafe() {
24    lock_guard<mutex> lock(myMutex);
25    // Critical section
26}  // Mutex automatically unlocked
27
28// Standard RAII classes
29// - unique_ptr, shared_ptr (memory)
30// - lock_guard, unique_lock (mutexes)
31// - fstream (files)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In