Reputation: 5260
#include "stdafx.h"
#include <functional>
#include <iostream>
#include <string>
std::function<void(int)> Foo()
{
int v = 1;
int r = 2;
auto l = [v, &r](int i)
{
std::cout << v << " " << r << " " << i << std::endl;
};
return l;
}
int main()
{
auto func = Foo();
func(3);
return 0;
}
I think will print "1 2 3", however, it is "1 -858993460 3", why?
Upvotes: 1
Views: 57
Reputation: 172864
Because r
is captured by reference, but it's a local variable and will be destroyed immediately after Foo()
returns. For func(3);
the captured reference has become invalid, and deference on it leads to UB; anything is possible.
On the other hand, v
is captured by value, that means it will be copied into the lambda and then works well.
Upvotes: 2