5.2.7 · HinglishC++ Programming

Destructor — RAII principle

1,568 words7 min readRead in English

5.2.7 · Coding › C++ Programming


WHAT is a destructor?

"Lifetime end" kab hoti hai? Teen common cases:

  1. Ek local (stack) object scope se bahar jaata hai (} ya return/throw pe pahunche).
  2. Heap object par delete call hota hai (delete p;).
  3. Program/main khatam hota hai, static/global objects ko destroy karte hue.

WHY does RAII exist? (Pehle manual tarike ko sahi se samjho)

"Manual" approach theek lagti hai:

void f() {
    int* p = new int[100];   // acquire
    // ... use p ...
    delete[] p;              // release
}

Yeh safe lagti hai kyunki delete[] wahan hai hi. Lekin agar // use p exception throw kare? Control seedha f se bahar jump karta hai, delete[] p skip hota hai → memory leak. Agar koi chhe mahine baad beech mein early return daal de? Wohi leak. Manual cleanup sirf happy path par hi sahi hota hai.


HOW to build an RAII wrapper (scratch se derivation)

Goal: raw memory ko safe banana. Step by step, har step par kyun poochte hue.

class IntArray {
    int* data;            // the owned resource
    size_t n;
public:
    IntArray(size_t size)              // ACQUIRE in constructor
        : data(new int[size]), n(size) {}   // Why? RAII: acquisition = initialization
 
    ~IntArray() { delete[] data; }    // RELEASE in destructor
                                      // Why? guaranteed to run on every exit path
 
    int& operator[](size_t i) { return data[i]; }   // Why? use it like an array
    size_t size() const { return n; }
};
 
void f() {
    IntArray a(100);   // acquire
    a[0] = 42;
    // ... even if this throws, ~IntArray runs and frees data ...
}                      // destructor fires here — automatic delete[]

Yeh exception path par kyun kaam karta hai: stack unwinding ke dauran, stack par har fully-constructed local object ka destructor call hota hai. a unme se ek hai ⇒ koi leak nahi.

Figure — Destructor — RAII principle

Order of destruction (LIFO rule)

Ulta kyun? Baad ke objects pehle walon par depend kar sakte hain. LIFO order mein todna guarantee karta hai ki jo cheez use ho rahi hai woh abhi bhi zinda hai jab use karne wali cheez destroy ho rahi hoti hai.


Worked examples


Recall Feynman: 12-saal ke bache ko samjhao

Socho tum ek library book (woh resource) lete ho. Khud return karne ka bharosa rakhne ke bajaye, tum ek magic backpack banate ho: jis pal book andar dalte ho, ek timer shuru hota hai, aur jab tum building se bahar jaate ho toh backpack automatically book return kar deta hai — chahe tum hadbadi mein bhaago (exception!). Backpack C++ object hai, book dalna constructor hai, aur auto-return destructor hai. Tum kabhi nahi bhulte, kyunki building ka exit (end of scope) tumhare liye return karta hai.


Flashcards

What does RAII stand for and what is its core idea?
Resource Acquisition Is Initialization — resource ki lifetime ko ek object se jodo: constructor mein acquire karo, destructor mein release karo, taaki cleanup automatic aur exception-safe ho.
When exactly does a destructor run?
Automatically jab object ki lifetime khatam hoti hai: local scope se bahar jaata hai, heap object par delete, ya statics/globals ke liye program end; exception se stack unwinding ke dauran bhi.
Why is RAII safer than manual new/delete?
Destructors har exit path par run hone ki guarantee hoti hai, exceptions aur early returns sameta, toh resource hamesha release hota hai; manual cleanup exception ya early return se skip ho jaati hai.
What is the Rule of Three?
Agar tum destructor, copy constructor, YA copy assignment define karo, toh lagbhag zaroor teeno chahiye — kyunki raw resource own karne ka matlab hai default shallow copies double-free/aliasing bugs karte hain.
Why must a polymorphic base class have a virtual destructor?
Taaki delete base_ptr; derived destructor invoke kare (phir base wala); virtual ke bina sirf base destructor run hota hai, derived resources leak karte hain.
In what order are objects destroyed?
Construction ka ulta (LIFO). Ek object ke liye: derived body, phir members reverse declaration order mein, phir base class.
Can a destructor take parameters or be overloaded?
Nahi — iske koi parameters nahi, koi return type nahi, aur ek class mein exactly ek hota hai.
What is the Rule of Zero?
Classes design karo jo koi raw resources own na karen (vector, unique_ptr, etc. use karo) taaki koi custom destructor/copy/move ki zaroorat hi na ho.

Connections

Concept Map

must be

fails on

causes

acquire =

release =

ties lifetime to

end triggers

runs during

guarantees

prevents

implements

Resource: memory, file, lock

Released eventually

Manual delete cleanup

Exception or early return

Resource leak

RAII principle

Constructor grabs resource

Destructor frees resource

Object lifetime

Stack unwinding

Unconditional cleanup

IntArray wrapper