I saw the equivalent of this code earlier, and I was a little surprised to learn that it worked as intended:
#include <iostream>
int main()
{
int a = 10;
[=]() mutable {
[&]() {
a += 10;
std::cout << "nested lambda: a=" << a << std::endl;
}(); // call nested lambda
}(); // call first lambda
std::cout << "a=" << a << std::endl;
}
As was desired, the output is
nested lambda: a=20
a=10
I was surprised that the compiler figures out that a
is used in the nested lambda, and correctly captures it by value in the first lambda even though it is not explicitly used there. I.e., the compiler must make the connection between the a
in the nested lambda, and a
in the outer scope. I thought that the argument capture would need to be explicit (i.e. [a]
in the first lambda, [&a]
in the nested), for it to work.
What are the deduction rules for automatic argument capture?