Lambdas Capture All In Context
If we have other variables than "c", we have access to it inside the lambda function. What we will have inside is a copy.
int c{42};
auto func = [=]() { std::cout << "inner value: " << c << std::endl; };
for (size_t i{}; i < 5; ++i) {
std::cout << "outer value: " << c << std::endl;
func();
++c;
}
- Capture everything by reference: we can do pretty nasty things with this, because the changes you'll do inside the lambda function are going to be visible outside. Make sure this is what you want to do.
int c{42};
auto func = [&]() { std::cout << "inner value: " << c << std::endl; };
for (size_t i{}; i < 5; ++i) {
std::cout << "outer value: " << c << std::endl;
func();
++c;
}