What is the difference between capturing by value and by reference?
Short answer
Capturing by value copies the variable into the closure at creation time, so later changes to the original don't affect the lambda and the copy is safe to use after the original's scope ends.
Advertisement
AModel answer
Capturing by value copies the variable into the closure at creation time, so later changes to the original don't affect the lambda and the copy is safe to use after the original's scope ends. Capturing by reference stores a reference, so the lambda sees later changes but causes dangling references if it outlives the captured variable.
int x = 1;
auto v = [x] { return x; }; // frozen at 1
auto r = [&x] { return x; }; // reflects later x
x = 99;Real-world example
Capturing a local by reference in a lambda stored for later use causes a dangling-reference crash.
Likely follow-ups
- When is by-reference capture dangerous? | Does by-value reflect later changes?
Related topics