4

I am not sure if I have defined behaviour in the following situation:

My Function pointer type:

typedef void (*DoAfter_cb_type)(void);

The Function which should assign callbacks:

void DoSomething(DoAfter_cb_type & DoAfter_cb)
{
    //...
    DoAfter_cb =  [](){
        //...
    };
}

Caller:

DoAfter_cb_type DoAfter_cb = nullptr;

DoSomething(DoAfter_cb);

// Here is something that has to be done after DoSomething but before DoAfter_cb.

if( DoAfter_cb != nullptr){
    DoAfter_cb();
}

As I learned here lambdas can be implicitly converted to function pointers.

However thoose are still pointers and I fear that something important for calling the lambda is stored on stack and would be out of scope if I just return the function pointer

I have to use function pointers because i do not have access to std::function in my environment. With std::function I would expect the lambda object to be stored in the reference variable and I would not have any problems.

Is the behaviour the same as If I would just define an ordinary function or do I have any side effects here?

mile4712
  • 45
  • 4

1 Answers1

5

Is the behaviour the same as If I would just define an ordinary function or do I have any side effects here?

Yes, it's the same. A captureless lambda is convertible to a regular function pointer because, to quote the C++ standard ([expr.prim.lambda.closure]/6, emphasis mine):

The closure type for a non-generic lambda-expression with no lambda-capture has a conversion function to pointer to function with C++ language linkage having the same parameter and return types as the closure type's function call operator. The conversion is to “pointer to noexcept function” if the function call operator has a non-throwing exception specification. The value returned by this conversion function is the address of a function F that, when invoked, has the same effect as invoking the closure type's function call operator.

So while the lambda goes out of scope, that pointer is backed by a proper function, just as if you had written it yourself at file scope. Functions "live" throughout the entire execution of the program, so the pointer will be valid, always.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • How to understand the said "**non-generic** lambda-expression"? What are the differences between "non-generic lambda" and "generic lambda"? – John Aug 25 '23 at 03:14