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

4
  • Does this answer your question? Commented Jul 27, 2020 at 17:22
  • 1
    As long as there's no capturing. Commented Jul 27, 2020 at 17:25
  • Why not use std::function<void()> 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. Commented Jul 27, 2020 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. Commented Jul 28, 2020 at 3:38

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

And if my lambda takes in parameters by value I guess that will also be a yes correct? Thanks for the help @super
No. A local object is created with the captured value in it, which then goes out of scope.
So to be safe it will be best to declare the callback functions in global scope correct?
@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)).
@MartinYork This: stackoverflow.com/a/28746827/2378102 . Furthermore you can put a + infront of a capturing lambda for some magic, check it out!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.