Home > Blockchain >  Return lambda with capture from a function in c 11
Return lambda with capture from a function in c 11

Time:06-02

The standard 5.1.2 6 says that there is a conversion function from a lambda expression without capture to the corresponding function pointer type. What about lambdas with capture? The following code compiles without warnings. Does this lead to undefined behavior?

std::function<void()> makeFucntion(int& parameter)
{
    return [&parameter]() // convert the lambda to std::function
    {
        cout << parameter;
    };
}

int var = 4;
auto foo = makeFucntion(var);
foo();

And if there is undefined behavior, is there another way to return a lambda expression with a capture from a function in c 11?

CodePudding user response:

std::function<void()> is not a function pointer. std::function<void()> can store more than just function pointers.

If you'd try to return a function pointer void(*)() then the code would fail to compile, because lambdas with capture do not have a conversion to function pointer.

As parameter is passed and capture by referene and var is still in scope while you call foo() the code is fine.

  • Related