C ++ Lambda按值捕获 [英] c++ lambda capture by value

查看:200
本文介绍了C ++ Lambda按值捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这本书的第3章中的C ++ lambda部分,以下代码使我感到困惑:

I am reading through the C++ lambda section in chapter 3 of this book and the following code confuses me:

int x = 0;
int y = 42;
auto qqq = [x, &y] {
    std::cout << "x: " << x << std::endl;
    std::cout << "y: " << y << std::endl;
    ++y;
};
x = y = 77;
qqq();
qqq();
std::cout << "final y: " << y << std::endl;

此代码输出:

x: 0
y: 77
x: 0
y: 78
final y: 79

为什么qqq()没有注册x已更改为77?有人说,按值传递意味着我们可以在定义lambda的地方读取但不能修改可读的数据。

Why does qqq() not register that x has changed to 77? It was stated that passing by value means we can read but not modify data readable where the lambda was defined. Does that mean we can't see changes after it's definition?

推荐答案

那是因为变量是按值捕获的(即复制的),这是否意味着我们在定义后看不到更改?定义lambda时仅一次。您可能会认为它没有更新。该代码大致等效于:

That's because the variable is captured by value (i.e. copied) only once, when you define the lambda. It's not "updated" as you may believe. The code is roughly equivalent to:

#include <iostream>

int x = 0;
struct Lambda
{
    int _internal_x; // this is used to "capture" x ONLY ONCE
    Lambda(): _internal_x(x) {} // we "capture" it at construction, no updates after
    void operator()() const
    {
        std::cout << _internal_x << std::endl;
    }
} qqq; 

int main()
{
    qqq(); 
    x = 77; // this has no effect on the internal state of the lambda
    qqq();
}

在Coliru上直播

这篇关于C ++ Lambda按值捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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