RAII Pattern
RAII (Resource Acquisition Is Initialization) C++ ki sabse important design philosophy hai — resource (memory, file handle, network connection, mutex lock) ko object ke constructor mein "acquire" karo, aur destructor mein "release" karo. Isse resource ki lifetime, object ki lifetime se automatically tied ho jaati hai.
Fayda: chahe function normally return ho, ya exception throw ho (stack unwinding), destructor GUARANTEED chalta hai — resource kabhi leak nahi hoti, manually cleanup code likhne ki zaroorat nahi. smart pointers, std::vector, std::string — sab RAII ka use karte hain.
class FileRAII {
FILE *file;
public:
FileRAII(const char* filename) {
file = fopen(filename, "w"); // acquire in constructor
}
~FileRAII() {
if (file) fclose(file); // release in destructor — GUARANTEED
}
void write(const char* text) {
fprintf(file, "%s", text);
}
};
void process() {
FileRAII f("data.txt");
f.write("Hello");
// agar yaha exception bhi aa jaaye, ~FileRAII() phir bhi chalega — file band hogi
} // scope khatam — automatic cleanup, chahe kuch bhi ho- Resource acquire = constructor mein, release = destructor mein
- Exception aane par bhi destructor guaranteed chalta hai
- smart pointers, vector, string — sab RAII follow karte hain
Multi-threaded code mein mutex.lock()/unlock() manually call karna dangerous hai — agar beech mein exception aa jaaye, unlock() kabhi nahi chalega (deadlock risk). std::lock_guard RAII use karke, constructor mein lock karta hai, destructor mein automatically unlock — chahe exception aaye ya na aaye.
#include <mutex>
mutex mtx;
void safeIncrement(int &counter) {
lock_guard<mutex> lock(mtx); // constructor mein lock hota hai
counter++;
// koi manual unlock nahi — destructor scope khatam hote hi unlock karega
} // yahi automatically unlock ho jaata hai, exception aaye ya na aayeAgar ek class custom destructor likhti hai (resource cleanup ke liye), usually copy constructor aur copy assignment operator bhi custom likhne padte hain ("Rule of Three") — warna default (shallow) copy behavior resource ko do baar free karne jaisi bugs de sakta hai. Modern C++ (C++11+) mein move constructor/move assignment bhi add hota hai ("Rule of Five").
class Buffer {
int *data;
public:
Buffer(int size) { data = new int[size]; }
~Buffer() { delete[] data; } // custom destructor
Buffer(const Buffer &other) { // Rule of Three: copy constructor
data = new int[/* size */]; // deep copy zaroori
}
Buffer& operator=(const Buffer &other) { /* ... */ return *this; } // copy assignment
};