简体   繁体   English

如何返回包含函数捕获的 lambda 函数? (C++)

[英]How to return a lambda function containing a function capture? (C++)

I am new to this Lambda function in C++.我是 C++ 中这个 Lambda 函数的新手。 I wanted to return a lambda function containing a function capture like this:我想返回一个包含函数捕获的 lambda 函数,如下所示:

#include<bits/stdc++.h>

//typedef void(*func1)();

auto func(void(*func2)())
{
    return [&func2](){cout<<"hello world 1"<<endl;func2();};
}

void func2()
{
    cout<<"hello world 2"<<endl;
}


int main()
{

    func(func2)();


    return 0;
}

But this snippet, upon execution, exits with a non zero number.但是这个片段在执行时会以非零数字退出。 Also, the func2() is not executed.此外,不会执行 func2()。 Please let me know how to fix this and also tell me the actual format of that auto portion.请让我知道如何解决这个问题,并告诉我该自动部分的实际格式。 Thanks in advance.提前致谢。

The lambda that you return from func :您从func返回的 lambda :

return [&func2]() {
  // ...
};

is capturing func2 by reference.正在通过引用捕获func2 Since func2 is local to func , this reference is dangling when you return from func .由于func2func局部func ,因此当您从func返回时,此引用是悬空的。 So in main , you get undefined behavior when func2 is called in the body of the lambda.因此,在main ,当在 lambda 的主体中调用func2时,您会得到未定义的行为。

You can fix this by making the lambda capture func2 by copy:您可以通过复制使 lambda 捕获func2来解决此问题:

return [func2]() {
  // ...
}

Here's a demo .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM