cpp core · high
Lambda Captures: [=] vs [&]
How a lambda captures the enclosing scope: [=] takes a snapshot copy, [&] references the live variables (and can dangle).
🔑 Key line
[=] captures by value (snapshot); [&] captures by reference (live, can dangle). Never let a [&] lambda outlive what it captured.
The code
int x = 1, y = 2;auto byVal = [=] { return x + y; }; // copies x, y (snapshot)auto byRef = [&] { return x + y; }; // references x, y (live)x = 99; // byVal: 1+2 byRef: 99+2
// Dangling captureauto make() { int local = 5; return [&] { return local; }; // local dies when make() returns!}What this lesson walks through
- 01A lambda's capture list
- 02[=] captures by value (a snapshot)
- 03Later changes don't affect the copy
- 04[&] captures by reference (live)
- 05By-reference sees later changes
- 06Danger: dangling reference
- 07The rule
A lambda can use variables from its enclosing scope, but only what its capture list grabs - and the capture mode decides whether it copies or references them.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Lambda Captures: [=] vs [&] and 100+ animated C++ interview lessons.