A lambda with a dangling reference...

Hi,

I have a lambda with a dangling reference (i.e. it captures by reference a number passed by value, i_ below):


1
2
3
4
5
6
template <typename T> auto f1(T i_)
{ // return a lambda with a dangling reference     
  // since i_ will go out of scope at the return of the function     
	auto lambda = [&] {return  i_ + 3; };
		return lambda;
}


I expect the following code to behave badly (accessing a dangling reference), but it does not!

1
2
3
4
5
6
7
8
void test()
{
	auto lamda_missingRef = f1(2);

	// i_ is out of scope - it's non existent after the return of f1...
        // this should not behave correctly (should not return 5)
	int a_missingRef = lamda_missingRef();
}


Why does calling lambda_missingRef() work?

Regards,
Juan Dent
Since the behavior is undefined, all behaviors, including working, are permissible.
it captures by reference
Really?
it captures by reference because it has [&] in the lambda..
Topic archived. No new replies allowed.