I think the dangling reference problem you mentioned is the main pitfall.
One other thing that is sometimes overlooked however, is that even when one uses a capture-by-value-lambda in a member function, it doesn't create a copy of the used member variables, but only makes a copy of the this
pointer.
For one, this means that you are again open to the dangling pointer Problem and second, you might accidentally modify variables outside of the scope of the lambda, even when it looks like, you are only modifying a local copy.
E.g. this will print 0 1 1
instead of 0 1 0
struct Foo {
int bar=0;
int bas() {
auto inc = [=]() {
bar++; //this is equivalent to this->bar++
return bar;
};
return inc();
}
};
int main() {
Foo foo;
std::cout << foo.bar <<" ";
std::cout << foo.bas() << " ";
std::cout << foo.bar << std::endl;
}
EDIT:
Just to avoid confusion related to the point made by @Snps:
If bar
was a local variable in bas()
(and thus be captured by value), the above lambda would not compile, as by-value-captured-variables are by default const, unless you explicitly specify the lambda as mutable.
So if you think about it, it is clear that bar is not copied, but that's easily forgotten, when reading or writing code.