If the fibonacci (line 2) is a local makeFibonacci() function and therefore goes out of scope when the function exits, how can it be captured by reference and used recursively?
Just the likelihood that the function is working properly. You have undefined behavior. You are referencing an object that is outside the scope.
Also, why the segfault program when capturing a lambda copy?
This is due to the initialization of std::function . First lambda is initialized, then std::function initialized by lambda. This means that you are copying an instance of std::function that is not initialized, and therefore it is probably not in a state that can allow good copies. The invariants are broken inside, which probably causes a segmentation error.
You can make a recursive lambda function more efficiently without std::function using a polymorphic lambda as follows
auto makeFibonacci() { auto fib = [](int n, auto& self) { if (n == 1) { return 1; } if (n == 2) { return 1; } return self(n - 1, self) + self(n - 2, self); }; return [fib](int n) { return fib(n, fib); }; };
Here lambda owns all the state it needs. Then you can use it as
auto fibonacci = makeFibonacci(); cout << fibonacci(6) << endl;
Also note that this is probably the worst way to calculate the fibonacci number .
Curious
source share