Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return lambda with capture from a function in c++11

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading