Lambdas
Contents
Dangling Reference
We need to be careful that if we capture the variables by reference then that variable does not go out of scope when we use the lambda object.File: dangle1.cpp
#include <iostream> #include <functional> std::function<int()> make_adder(int x1) { return [&x1]() { return x1 + 1; }; } int main() { auto add_one = make_adder(5); std::cout << add_one() << std::endl; // This will likely cause a crash or undefined behavior return 0; }
From the above file we have: std::functionmake_adder(int x1) { return [&x1]() { return x1 + 1; }; } This is clearly wrong. The "x1" is a local variable to the function "make_adder" . When we use it: auto add_one = make_adder(5); std::cout << add_one() << std::endl; // This will likely cause a crash or undefined behavior When the lambda "add_one" is used in the cout statement the return value is referencing the local variable "x1" that has gone out of scope. The behavior at this point is undefined. This is the same problem that we encounter with a local reference such as: int& function1() { int x1 = 5 ; return x1 ; } When the "function1()" is called from some other place in the code then the value being to referred to has gone out of scope.
Exercise
1) Correct the issue in the program. Note "f1" is defined as a function. Could it have been defined as a lambda expression ?File: dangle_ex1.cpp
Solutions
File: lambdas_ex1s.cpp