本文介绍了返回lambda捕获函数参数参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream>#include< functional>使用命名空间std;std :: function< void(void)>makeLambda(int参数){返回[& param](){cout<<参数<<endl;};}int main(){自动回调= makeLambda(5);打回来();} 

基于 lambda描述,它如下看起来程序将导致未定义的行为,因为调用回调时,捕获的var,函数参数不在范围内.但我看到它总是可以打印5.

我的g ++版本是gcc-4.9.1.

为什么可以工作?

解决方案

您注意到,这是未定义的行为.任何事情都可能发生,包括看起来可行.如果您切换编译器,更改标志,忘记洗碗或一个小时后起床,则可能会得到完全不同的结果.

例如,Clang 打印32767 的某些版本和标志集./p>

#include <iostream>
#include <functional>

using namespace std;

std::function<void(void)> makeLambda(int param)
{
    return [&param](){cout << param << endl;};
}

int main()
{
    auto callback = makeLambda(5);
    callback();
}

Based on lambda description as following, it looks the program will cause an undefined behavior because when callback is invoked, the captured var, function parameter, is out-of-scope. But I see it always can print 5.

My g++ version is gcc-4.9.1.

Why can it work?

解决方案

As you note, this is undefined behaviour. Anything can happen, including appearing to work. If you switch compiler, change flags, forget to do the dishes, or get up an hour later, you could get completely different results.

As an example, Clang prints 32767 for some version and set of flags.

这篇关于返回lambda捕获函数参数参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 05:35