🎁
Memory Management

RAII Pattern

Resource Acquisition Is Initialization
💡 RAII ek hotel checkout jaisa hai jo automatic hai — jab tum apna room (object) chhodte ho, hotel khud hi cleanup kar deta hai (keys collect, room clean) — tumhe manually kuch yaad nahi rakhna padta.

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
🎁
RAII ek hotel checkout jaisa hai jo automatic hai — jab tum apna room (object) chhodte ho, hotel khud hi cleanup kar deta hai (keys collect, room clean) — tumhe manually kuch yaad nahi rakhna padta.
1 / 2
⚡ झट से Recap
  • Resource acquire = constructor mein, release = destructor mein
  • Exception aane par bhi destructor guaranteed chalta hai
  • smart pointers, vector, string — sab RAII follow karte hain
इस page में (2 subtopics)

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 aaye
💡Tip: RAII sirf memory tak limited nahi hai — locks, file handles, network sockets, database connections, sab "acquire-then-must-release" resources RAII pattern se safely manage hote hain.

Agar 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
};
⚠️Common Mistake: Agar sirf custom destructor likho (copy constructor/assignment nahi), default shallow-copy behavior do objects ko SAME memory point karwa dega — jab dono destroy honge, same memory do baar delete hogi ("double-free" crash).