如何捕获列表的lambda实际工作在C ++ 11? [英] How do capture lists of lambdas actually work in C++11?

查看:134
本文介绍了如何捕获列表的lambda实际工作在C ++ 11?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道捕获列表使变量在lambda函数体内可用,如下所示:

I know that capture lists make variables available inside a lambda function body like so:

int pos(0);
std::function<void()> incPos = [&pos](){ ++pos; };
incPos(); //pos is now 1

但是这种捕获如何在编译器级别上工作呢?

But how does that capturing actually work on compiler level? Where are the captured addresses or captured values stored?

推荐答案

每个lambda表达式都会生成一个唯一的函数对象变量作为数据成员。例如,你的代码中的lambda表达式将被编译器转换成这样:

Each lambda expression generates a unique function object (closure) that stores the captured variables as data members. For instance, the lambda expression in your code would be transformed into something like this by the compiler:

struct __uniquely_named_lambda
{
  __uniquely_named_lambda(int& pos)
  : pos(pos) {}
  int& pos;

  void operator()() const
  { ++pos; }
};

调用lambda只是调用 operator $ c>。

Invoking the lambda is simply a call to operator().

数据成员是引用,因为您通过引用捕获。如果你通过值捕获它将是一个简单的 int 。另请注意,默认情况下生成的 operator() const 。这就是为什么你不能修改捕获的变量,除非你使用 mutable 关键字。

The data member is a reference since you captured by reference. If you captured by value it would be a plain int. Also note that generated operator() is const by default. This is why you cannot modify captured variables unless you use the mutable keyword.

这篇关于如何捕获列表的lambda实际工作在C ++ 11?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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