Search code examples
c++c++11lambdadangling-pointer

Dangling reference in inner lambda


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?


Solution

  • 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.