5.2.22 · D3C++ Programming

Worked examples — Lambda expressions — capture list (by value, by reference)

2,239 words10 min readBack to topic

The scenario matrix

Every question about capture lists is really a question about two axes:

  1. How did we capture it? (copy vs alias, explicit vs default, mutable or not)
  2. Whose lifetime is longer — the lambda or the variable it captured?

Cross those and you get the complete grid. Each cell below is worked in an example.

# Cell Capture Key twist Example
A Snapshot [x] original changes after creation Ex 1
B Live wire [&x] original changes after creation Ex 2
C Editable copy [x] mutable copy persists across calls Ex 3
D Mixed default [=, &b] some copied, some aliased Ex 4
E Dangling (degenerate) [&x] escapes scope reference to dead variable Ex 5
F Zero / empty [] captures nothing — compile behaviour Ex 6
G Timing of the snapshot [x] created in a loop when the copy is taken Ex 7
H Real-world word problem [&total] accumulate a running sum Ex 8
I Exam twist [this] vs [*this] capturing the object Ex 9

The picture below is the whole matrix at a glance — keep it open as you read.

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

Worked examples










Recall Every cell, one line each

By value after original changes ::: still the frozen snapshot value. By reference after original changes ::: the current live value. [x] mutable across two calls ::: the internal copy persists and keeps climbing; original never moves. [=, &b] ::: default copy, but b aliased — copy edits stay inside, alias edits reach the real b. [&local] returned from a function ::: dangling reference → undefined behaviour. [] using an outside local ::: compile error; parameters are fine though. [i] in a loop vs [&i] ::: value snapshots each iteration; reference shares one (doomed) counter. [this] vs [*this] ::: pointer to the real object (can dangle) vs a full copy of the object.