4

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.

keith
  • 5,122
  • 3
  • 21
  • 50

2 Answers2

3

"whether the code will cause foo_ptr to dangle"

No. There is no dangling happening even if you replace that code with:

ptr = new <something>

Dangling pointer is created when a pointer is deleted (memory freed) and is Not assigned to nullptr (or 0). In this case, neither of that is happening.

Moreover, the address of lambda is not stored in freestore or stack, hence nothing to worry as such. The code is safe.

iammilind
  • 68,093
  • 33
  • 169
  • 336
0

In std C++ all code is always linked in and present, so a pointer to code never goes out of scope. Non syatic data however may go out of scope so so care may be needed to ensure pointers remain valid.

You are using a pure function pointer so everything should work fine.

doron
  • 27,972
  • 12
  • 65
  • 103