Reputation: 36048
Is it OK to declare lambdas in local scope like this:
// reference to method is just a call back function.
void(*referenceToSomeMethod)();
// store call back function
void foo(void(*pointerToMethod)())
{
referenceToSomeMethod = pointerToMethod; // save reference to method
}
int main()
{
referenceToSomeMethod = nullptr;
if (1 == 1)
{
// use of lambda on local scope
foo([]() {
printf("Executing callback function\n");
});
} // leaving scope lambda may not longer be valid?
// simulate some work
Sleep(10000);
if (referenceToSomeMethod != nullptr)
referenceToSomeMethod(); // execute lambda
}
In real life I wait until an event occurs to fire the callback method. Can I run the risk of the callback pointer pointing to a function that no longer exists?
I know this works in c# and other languages that have a garbage collector. But will this work on c++?
Upvotes: 1
Views: 331
Reputation:
Lambdas with empty brackets are equivalent with function pointers and will be copied by value in the same way. Answer yes.
Upvotes: 2