1

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++?

Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • Does [this](https://stackoverflow.com/questions/8026170/lifetime-of-lambda-objects-in-relation-to-function-pointer-conversion?noredirect=1&lq=1) answer your question? – Cory Kramer Jul 27 '20 at 17:22
  • 1
    As long as there's no capturing. – QuentinUK Jul 27 '20 at 17:25
  • Why not use `std::function` and pass by r-value reference. Thus allowing you to capture the lambda and move it into place? Thus allowing you presrve any captured arguments. – Martin York Jul 27 '20 at 18:11
  • I cannot use std::function I am creating this a class library for a micro-controller (arduino). But yes I have to store the parameter as a reference somewhere else it is the same idea. – Tono Nam Jul 28 '20 at 03:38

1 Answers1

2

Lambdas with empty brackets are equivalent with function pointers and will be copied by value in the same way. Answer yes.

  • And if my lambda takes in parameters by value I guess that will also be a yes correct? Thanks for the help @super – Tono Nam Jul 27 '20 at 17:26
  • 1
    No. A local object is created with the captured value in it, which then goes out of scope. – QuentinUK Jul 27 '20 at 17:27
  • So to be safe it will be best to declare the callback functions in global scope correct? – Tono Nam Jul 27 '20 at 17:35
  • @super. I was unaware that lambdas with empty brackets were equivalent to function pointers. Do you have a reference for this (the above code works so it seems to be true (which actually surprised me)). – Martin York Jul 27 '20 at 18:12
  • 1
    @MartinYork This: https://stackoverflow.com/a/28746827/2378102 . Furthermore you can put a + infront of a capturing lambda for some magic, check it out! –  Jul 27 '20 at 19:03
  • @super Thanks that really helped. What does the `+` do? – Martin York Jul 27 '20 at 19:40