按值类成员捕获 [英] capture by value class members

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

问题描述

有一种方法,当在成员函数中编写lambda函数时,通过值捕获包围类的字段?缺省catch-all = 不工作,因为当我引用lambda中的变量时,我获取,而不是从捕获的this指针解除引用,以及显式命名变量在捕获列表中,因为我得到两个编译错误:捕获的非变量< name> 'this' lambda函数

Is there a way, when writing a lambda function within a member function, to capture fields of the enclosing class by value? The default catch-all = doesn't work because when I reference the variable inside the lambda I get instead a dereferencing from the captured this pointer, as well as explicitly naming the variable in the capture list, because I get two compile error: capture of non-variable <name>, and ‘this’ was not captured for this lambda function

推荐答案

否,无法通过值捕获数据成员。 lambda只能捕获两种情况:

No, data members cannot be captured by value. A lambda can capture only two kinds of things:


  1. this

  2. 非静态局部变量(即具有自动存储持续时间的变量)。

在注释中注释为ildjarn,你可以创建一个局部变量与数据成员的值的副本,并通过值捕获该局部变量。

As has been noted by ildjarn in the comments, you can create a local variable with a copy of the value of the data member, and capture that local variable by value.

认为如果允许数据成员的显式按值捕获,则可能会导致混乱,因为显式捕获的行为与隐式捕获的行为不同。例如,给定一个 int 名为 m 的可访问数据成员,以下将产生不同的结果:

I would argue that if explicit by-value capture of a data member was allowed, it could prove confusing, since the behavior of explicit capture would differ from that of implicit capture. For example, given an accessible data member of type int named m, it would be odd that the following would produce different results:

[=] () mutable { m = 1; } // we modify this->m
[=m]() mutable { m = 1; } // we modify the copy of m that was captured

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

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