5.2.13 · D3 · HinglishC++ Programming

Worked examplesRAII — resource acquisition is initialization — why it's the key idiom

2,609 words12 min read↑ Read in English

5.2.13 · D3 · Coding › C++ Programming › RAII — resource acquisition is initialization — why it's the

Yeh page RAII idiom ko har tarah ki situation mein walk karta hai jisme use survive karna hota hai. Parent note ne bataya tha ki RAII kya hai; yahan hum usse prove karte hain — har corner case ko hit karke — happy path, exception path, double-owner trap, empty resource, nested scope, aur ek exam-style twist.

Har example se pehle, forecast karo: khud guess karo answer. Phir check karo.


Scenario matrix

Har "resource lifetime" problem inhi cells mein se kisi ek mein aata hai. Hum har ek ko hit karenge.

Cell Kya trigger karta hai Danger agar RAII absent ho Example
A. Normal exit function cleanly return karta hai kuch nahi (lekin hand-cleanup verbose hota hai) Ex 1
B. Exception exit koi callee mid-function throw karta hai resource leak / locked rehta hai Ex 2
C. Early return / break cleanup se pehle if(...) return; release skip ho jaata hai Ex 3
D. Copy of an owner ek owner ko doosre mein assign/copy kiya double-free Ex 4
E. Move (steal) ownership transfer ho jaati hai double-free YA no free Ex 5
F. Empty / null resource acquisition fail hua ya moved-from hai destructor no-op hona chahiye Ex 6
G. Nested / reverse order ek scope mein kai owners galat teardown order → use-after-free Ex 7
H. Real-world word problem file + lock saath mein leak + deadlock combined Ex 8
I. Exam twist (throwing dtor) destructor throws while unwinding std::terminate Ex 9

Har cell letter apne example pe ek tag ki tarah lagta hai. Saath mein yeh poora space tile kar dete hain un cheezoon ka jo galat ho sakti hain jab ek resource acquire hota hai.

Jinpe hum rely karte hain: Constructors and Destructors, Stack Unwinding and Exceptions, Smart Pointers - unique_ptr shared_ptr, Rule of Three Five Zero, Move Semantics, Exception Safety Guarantees, aur std::lock_guard and Mutexes.


Examples ke liye counting model

Cleanup ko numbers se checkable banane ke liye, socho ki har resource ek global ledger maintain karta hai:

Figure dekho: black line live ko time ke saath trace karti hai. RAII use 0 tak ek clean staircase mein wapas laata hai.

Figure — RAII — resource acquisition is initialization — why it's the key idiom

Worked examples


Recall

Recall Har danger matrix ka kaunsa cell hai?
  • Exception par leak ::: Cell B — stack unwinding destructor run karke fix karta hai.
  • if(...) return; par skipped cleanup ::: Cell C — har exit path destructor run karta hai.
  • Same address do baar free ::: Cell D — raw-pointer owner ka default copy; Rule of Five / unique_ptr se fix karo.
  • Emptied object safely destroy ho sakta hai ::: Cell F — destructor null case guard karta hai (no-op).
  • Cleanup se std::terminate ::: Cell I — unwinding ke dauran throwing destructor; use noexcept banao.