Captures
A capture is how a lambda reaches variables from the enclosing scope. [x] copies x into the closure, [&x] stores a reference, [=] copies everything used, [&] references everything used. Captures are initialised when the lambda is created, not when it is called.
Detailed Explanation
A lambda's parameter list describes what the caller passes at the call. Captures describe what the lambda already knows from the function that created it. You are filtering sessions older than now. now is a local. The predicate needs it. You write [now](const Session& s) { return s.expiry < now; }. The closure object contains a copy of now. The predicate can outlive the current stack frame only if that copy is enough.
The capture clause is the first thing in the lambda, inside [].
| Clause | Meaning |
|---|---|
[] | No locals. Only globals, statics, and parameters of the lambda. |
[x] | Copy x. The copy is const inside operator() unless the lambda is mutable. |
[&x] | Reference x. No copy. x must still be alive when the lambda runs. |
[=] | Copy every automatic variable the body uses. |
[&] | Reference every automatic variable the body uses. |
[=, &x] | Default copy, but x by reference. |
[&, x] | Default reference, but x by copy. |
[x = expr] | C++14 init-capture: a new data member initialised from expr. |
[this] | Copy the pointer this (not the object). Members are accessed through it. |
[*this] | C++17: copy the object *this into the closure. |
Initialisation happens at the lambda expression, once. If you capture x by copy and then change the local x, the closure still has the old value. If you capture by reference and change the local, the next call sees the new value.
That timing is why dangling captures happen. You write [&]{ return total; } and return the lambda from the function. total is a local. The caller invokes the lambda later. The reference points at dead stack. The same bug happens when you pass a referencing lambda to std::async or std::thread and the launching function ends first. Capture by value, or capture a std::shared_ptr you own, or keep the locals alive until every asynchronous call finishes.
[=] and [&] are convenient and opaque. A reader cannot see which names are used without reading the body. Prefer an explicit list when the lambda leaves the current statement: [now, &out]. Default [&] is acceptable for a predicate you pass straight into std::for_each on this line, because the lambda dies before the locals do.
[this] is easy to get wrong. It captures the pointer, so data_ in the body means this->data_. If the lambda outlives the object (a callback stored on a heap queue, a std::function member that another object keeps), you have a dangling this. [*this] copies the object and is the safer default for a small value type. For a large type, copy the specific members you need: [id = id_, name = name_].
Init-captures move as well as copy: [p = std::move(ptr)] transfers a unique_ptr into the closure so the lambda can own it. That is the only way to move something into a lambda; [ptr] always copies, and unique_ptr is not copyable.
Code Examples
#include <iostream>
#include <vector>
int main() {
int threshold = 3;
std::vector<int> nums{1, 2, 4, 5};
int kept = 0;
for (int n : nums) {
auto above = [threshold](int x) { return x > threshold; };
if (above(n)) ++kept;
}
std::cout << kept << '\n'; // prints: 2
threshold = 10; // the copies inside above already exist
(void)threshold;
}#include <functional>
#include <iostream>
#include <string>
#include <utility>
std::function<void()> makeGreeter(std::string name) {
// Init-capture moves name into the closure so the lambda owns it.
return [name = std::move(name)] {
std::cout << "hi " << name << '\n';
};
}
int main() {
auto greet = makeGreeter("ada");
greet(); // prints: hi ada
}Common Gotchas
Returning a `[&]` lambda that names locals
the references die with the stack frame. Capture by value, or have the caller own the data.
`[this]` plus a destroyed object
storing `std::thread([this]{ use(data_); })` and then destroying `*this` is a use-after-free. Capture members, or keep the object alive with `shared_from_this`.
`[=]` in a member function still captures `this`
using `data_` in the body implicitly captures `this` by pointer, not a copy of `data_`. Write `[data = data_]` if you need a snapshot.
Default captures do not include statics and globals
you can name them without capturing. They have their own lifetime.