The following compiles. But is there ever any sort of dangling reference issue?
class Foo {
Foo(std::function<void(int)> fn) { /* etc */ }
}
void f(int i, Foo& foo) { /* stuff with i and foo */ }
Foo foo([&foo](int i){f(i, foo);});
Seems to work. (The real lambda is of course more complicated.)
That depends entirely on what you're doing with
Foo
. Here's an example that would have dangling reference issues:The lambda expression
[&foo](int i){f(i, foo);}
will lead compiler to generate a closure class something like this (but not totally correct) :Therefore, the declaration
Foo foo([&foo](int i){f(i, foo);});
is treated asFoo foo(_lambda(foo));
. Capturingfoo
itself when constructing does not has problem in this situation because only its address is required here (References are usually implemented via pointers).The type
std::function<void(int)>
will internally copy construct this lambda type, which means that Foo's constructor argumentfn
holds a copy of_lambda
object (that holds a reference (i.e., mFoo) to yourfoo
).These implies that dangling reference issue may arise in some situations, for example: