返回lambda捕获函数参数参考 [英] return a lambda capturing function parameter reference

查看:89
本文介绍了返回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.

悬挂引用

如果通过引用(隐式或显式)捕获实体,并且在关闭对象之后调用闭包对象的函数调用运算符实体的生命周期已结束,发生未定义的行为.C ++闭包不会延长捕获引用的生存期.

同样适用于捕获对象指向的对象的生存期这个指针.

为什么可以工作?

解决方案

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

例如,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.

Dangling references

If an entity is captured by reference, implicitly or explicitly, and the function call operator of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of the captured references.

Same applies to the lifetime of the object pointed to by the captured this pointer.

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捕获函数参数参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆