5.2.22 · D3 · HinglishC++ Programming

Worked examplesLambda expressions — capture list (by value, by reference)

2,425 words11 min read↑ Read in English

5.2.22 · D3 · Coding › C++ Programming › Lambda expressions — capture list (by value, by reference)


Scenario matrix

Capture lists ke baare mein har sawaal actually do axes ke baare mein sawaal hai:

  1. Kaise capture kiya? (copy vs alias, explicit vs default, mutable hai ya nahi)
  2. Kiski lifetime zyada lambi hai — lambda ki ya us variable ki jise usne capture kiya?

Inhe cross karo aur tumhe complete grid milti hai. Neeche har cell ek example mein work ki gayi hai.

# Cell Capture Key twist Example
A Snapshot [x] original creation ke baad change hota hai Ex 1
B Live wire [&x] original creation ke baad change hota hai Ex 2
C Editable copy [x] mutable copy calls ke across persist karti hai Ex 3
D Mixed default [=, &b] kuch copied, kuch aliased Ex 4
E Dangling (degenerate) [&x] scope se escape kare dead variable ka reference Ex 5
F Zero / empty [] kuch capture nahi — compile behaviour Ex 6
G Snapshot ki timing [x] loop mein create hoi copy kab li jaati hai Ex 7
H Real-world word problem [&total] running sum accumulate karna Ex 8
I Exam twist [this] vs [*this] object ko capture karna Ex 9

Neeche ki picture ek nazar mein poora matrix hai — padhte waqt ise khula rakho.

Figure — Lambda expressions — capture list (by value, by reference)

Worked examples










Recall Har cell, ek-ek line mein

Original change hone ke baad by value ::: frozen snapshot value abhi bhi wahi rahti. Original change hone ke baad by reference ::: current live value milti hai. [x] mutable do calls ke across ::: internal copy persist karti aur badhti rehti hai; original kabhi nahi hilta. [=, &b] ::: default copy, lekin b aliased — copy edits andar rahte hain, alias edits real b tak pahunchte hain. [&local] function se return hone par ::: dangling reference → undefined behaviour. [] bahar ke local ko use karte hue ::: compile error; parameters theek hain though. Loop mein [i] vs [&i] ::: value har iteration ko snapshot karta hai; reference ek (doomed) counter share karta hai. [this] vs [*this] ::: real object ka pointer (dangle ho sakta hai) vs object ki full copy.