Reputation: 11
I am new to this Lambda function in C++. I wanted to return a lambda function containing a function capture like this:
#include<bits/stdc++.h>
//typedef void(*func1)();
auto func(void(*func2)())
{
return [&func2](){cout<<"hello world 1"<<endl;func2();};
}
void func2()
{
cout<<"hello world 2"<<endl;
}
int main()
{
func(func2)();
return 0;
}
But this snippet, upon execution, exits with a non zero number. Also, the func2() is not executed. Please let me know how to fix this and also tell me the actual format of that auto portion. Thanks in advance.
Upvotes: 0
Views: 88
Reputation: 60218
The lambda that you return from func
:
return [&func2]() {
// ...
};
is capturing func2
by reference. Since func2
is local to func
, this reference is dangling when you return from func
. So in main
, you get undefined behavior when func2
is called in the body of the lambda.
You can fix this by making the lambda capture func2
by copy:
return [func2]() {
// ...
}
Here's a demo.
Upvotes: 2