I've recently seen some production C++ code assign a lambda to a function pointer and allow the lambda to go out of scope. I was wondering if this will lead to a dangling pointer to the lambda. My reproduction of the code is below. I was wondering whether the code will cause foo_ptr
to dangle:
#include <iostream>
using foo_ptr = void(*)();
int main()
{
foo_ptr ptr{ nullptr };
{
ptr = []()
{
std::cout << "foo" << std::endl;
};
}
// Question: is ptr dangling?
ptr();
std::cout << "Done...";
std::getchar();
return EXIT_SUCCESS;
}
I think the answer is yes because the lambda goes out of scope and will be destroyed, but because this used in production code I wondered if there is more to it.