Reputation: 657
#include <iostream>
#include <functional>
using namespace std;
std::function<void(void)> makeLambda(int param)
{
return [¶m](){cout << param << endl;};
}
int main()
{
auto callback = makeLambda(5);
callback();
}
Based on lambda description as following, it looks the program will cause an undefined behavior because when callback is invoked, the captured var, function parameter, is out-of-scope. But I see it always can print 5.
My g++ version is gcc-4.9.1.
Dangling references
If an entity is captured by reference, implicitly or explicitly, and the function call operator of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of the captured references.
Same applies to the lifetime of the object pointed to by the captured this pointer.
Why can it work?
Upvotes: 2
Views: 56
Reputation: 65600
As you note, this is undefined behaviour. Anything can happen, including appearing to work. If you switch compiler, change flags, forget to do the dishes, or get up an hour later, you could get completely different results.
As an example, Clang prints 32767 for some version and set of flags.
Upvotes: 3