C ++ lambda表达式的生命周期是什么? [英] What is the lifetime of a C++ lambda expression?

查看:3548
本文介绍了C ++ lambda表达式的生命周期是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我已阅读什么是生命周期lambda

(I have read What is the lifetime of lambda-derived implicit functors in C++? already and it does not answer this question.)

我理解C ++ lambda语法只是用于制作实例的糖的匿名类与一个调用操作符和一些状态,我理解该状态的生存期要求(由是否通过引用的值来决定)。但lambda对象本身的生命周期是什么?在下面的例子中, std :: function 实例返回有用吗?

I understand that C++ lambda syntax is just sugar for making an instance of an anonymous class with a call operator and some state, and I understand the lifetime requirements of that state (decided by whether you capture by value of by reference.) But what is the lifetime of the lambda object itself? In the following example, is the std::function instance returned going to be useful?

std::function<int(int)> meta_add(int x) {
    auto add = [x](int y) { return x + y; };
    return add;
}

如果是,如何工作?这看起来对我有点太多的魔法 - 我只能想象它工作 std :: function 复制我的整个实例,这可能是非常重的,取决于我捕获 - 在过去,我使用 std :: function 主要与裸函数指针,并复制那些是快速。根据 std :: function 的类型擦除,它也似乎有问题。

If it is, how does it work? This seems a bit too much magic to me - I can only imagine it working by std::function copying my whole instance, which could be very heavy depending on what I captured - in the past I've used std::function primarily with bare function pointers, and copying those is quick. It also seems problematic in light of std::function's type erasure.

推荐答案

生命周期正是如果你用一个手工函数来替换你的lambda。

The lifetime is exactly what it would be if you replaced your lambda with a hand-rolled functor:

struct lambda {
   lambda(int x) : x(x) { }
   int operator ()(int y) { return x + y; }

private:
   int x;
};

std::function<int(int)> meta_add(int x) {
   lambda add(x);
   return add;
}

将创建对象 meta_add 函数,然后将[在其entirty中,包括 x ]的值移动到返回值中,那么本地实例将超出范围,被正常销毁。但是从函数返回的对象将保持有效,只要保存它的 std :: function 对象。这多长时间显然取决于调用上下文。

The object will be created, local to the meta_add function, then moved [in its entirty, including the value of x] into the return value, then the local instance will go out of scope and be destroyed as normal. But the object returned from the function will remain valid for as long as the std::function object that holds it does. How long that is obviously depends on the calling context.

这篇关于C ++ lambda表达式的生命周期是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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