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?

2
  • Didn't Boost have boost::function<> ? IIRC C++11 got it from there. Commented Apr 5, 2018 at 7:45
  • Unfortunately i can't use boost too. Commented Apr 5, 2018 at 8:08

1 Answer 1

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.

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

1 Comment

How to understand the said "non-generic lambda-expression"? What are the differences between "non-generic lambda" and "generic lambda"?

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.