I have an inner lambda that uses one of the referenced variables of the outer lambda like this:
int x=0;
auto outer=[&](){
return [&](){
x=5;
};
};
auto inner= outer();
inner();
std::cout << x;
I tried it. It worked well. However, I want to make sure that there is no dangling reference here. Is there?
There is no dangling reference here. The reference of the inner lambda is not a reference to a reference (there is no such thing); it refers to x
- which of course didn't go out of scope.
As shown, you're calling the lambda within the block scope where x
is declared, and there's no dangling reference.
It's worth noting that the inner anonymous lambda captures the reference to x
directly from the outermost block scope rather than from the outer lambda, since it's looking for the declaration.
If you pass (a copy of) your lambda object outside that block scope, then you can cause a dangling reference.
If you rewrite the code without using lambdas then I think it is clear there is no dangling reference, simply a reference to a variable x
that is still in scope:
class Inner {
int& x;
public:
Inner(int &x) : x(x) {}
void operator()(){
x = 5;
}
};
class Outer {
int& x;
public:
Outer(int &x) : x(x) {}
Inner operator()(){
return {x};
}
};
int main() {
int x=0;
auto outer = Outer{x};
auto inner = outer();
inner();
std::cout << x;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With