Lambda值捕获和“可变"捕获关键词 [英] Lambda capture by value and the "mutable" keyword

查看:72
本文介绍了Lambda值捕获和“可变"捕获关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lambdas中需要关键字mutable引起了极大的困惑.

The need of the keyword mutable in lambdas, is source of great confusion.

考虑代码:

int x = 10;

function<void()> lambda = [=]() mutable {x++; cout << "Inside lambda: x = " << x << "\n";};

cout << "Before lambda: x = " << x << "\n";
lambda();
cout << "After  lambda: x = " << x << "\n\n";

输出:

Before lambda: x = 10
Inside lambda: x = 11
After  lambda: x = 10

如我们所见,变量x在lambda之后保持不变,因此没有副作用.

As we can see, the variable x stays unchanged after the lambda, so there are no side effects.

但是,如果我们忘记"关键字可变,则会收到错误消息.

However, if we "forget" the keyword mutable, we get an error.

由于参数按值传递C ++中的默认值,因此对 mutable 关键字的需求对我而言没有意义.

Being the argument passing by value the default in C++, it doesn't make sense for me the need of the mutable keyword.

有人可以代替lambda编写(甚至用伪代码)编译器生成的类吗?

Can someone write (even in pseudo code) the class generated by the compiler, in place of the lambda?

谢谢

推荐答案

如上所述这里 mutable说明符允许lambda修改复制捕获的参数并调用其非const成员函数.它不会影响通过引用捕获的变量.

As mentioned here the mutable specifier allows the lambda to modify the parameters captured by copy and to call their non-const member functions. It doesn't affect variables captured by reference.

有人可以代替lambda编写(甚至用伪代码)编译器生成的类吗?

Can someone write (even in pseudo code) the class generated by the compiler, in place of the lambda?

给出一般案例并不容易,但是我们可以定义在您的特定案例中有效的内容.
生成的类可能看起来像:

It's not that easy to give a general case, but we can define something that is valid in your specific case.
The generated class would probably look like:

struct Lambda {
    void operator()() { x++; }
    int x{10};
};

如果删除mutable说明符,则将函数运算符定义为const:

If you remove the mutable specifier, the function operator is defined as const:

struct Lambda {
    void operator()() const { x++; }
    int x{10};
};

为简单起见,我已经使用给定值(10)初始化了x并将其公开,但是显然它是通过复制使用从周围上下文捕获的变量进行初始化的,并且不能从函数操作符外部进行访问.
就像您一样,也从用于初始化它的变量中推导出它的类型:

For simplicity I've initialized x with the given value (10) and made it public, but it's obviously initialized by copy using the variable captured from the surrounding context and not accessible from outside the function operator.
Its type is deduced as well from the variable used to initialize it as if you do:

auto lambda_x = x;

有关更多详细信息,请参见此处.

See here for further details.

这篇关于Lambda值捕获和“可变"捕获关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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