Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dangling reference in inner lambda [duplicate]

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?

like image 215
Humam Helfawi Avatar asked Apr 24 '17 09:04

Humam Helfawi


3 Answers

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.

like image 112
eerorika Avatar answered Oct 26 '22 02:10

eerorika


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.

like image 35
Useless Avatar answered Oct 26 '22 02:10

Useless


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;
}
like image 43
Chris Drew Avatar answered Oct 26 '22 03:10

Chris Drew