[英]Why can't a data member be in a lambda capture list
I have a class foo
that has bar
as a member variable. 我有一个类
foo
,它有一个bar
作为成员变量。
In another member function of the class, I'm writing a lambda function: 在该类的另一个成员函数中,我正在编写一个lambda函数:
[bar](void){}
But I can't include bar
in the capture list. 但我不能在捕获列表中包含
bar
。 Why is that? 这是为什么?
Only objects with automatic storage duration can be captured by a lambda in C++11 (ie local variables and function parameters). 只有具有自动存储持续时间的对象才能被C ++ 11中的lambda捕获(即局部变量和函数参数)。 If you want the effect of capturing a
non-static
class data member, you can either capture the this
pointer as in Danvil's answer : 如果你想要捕获一个
non-static
类数据成员的效果,你可以捕获this
指针,如Danvil的答案 :
auto f = [this]{ std::cout << a << std::endl; };
or cache the data member's value in a local variable and capture that: 或者将数据成员的值缓存在局部变量中并捕获:
auto a = this->a;
auto f = [a]{ std::cout << a << std::endl; };
which will be much more concise in C++14: 这将在C ++ 14中更加简洁:
auto f = [a = this->a]{ std::cout << a << std::endl; };
The choice between these two options depends on whether you want to store the value a
has right now or if you want to retrieve the value a
has when the lambda is called . 这两个选项之间的选择取决于是否要存储值
a
具有现在或者如果你想检索值a
具有当拉姆达被调用 。 Note that in the case where this
is captured you must ensure that the lifetime of the pointer object encloses the lifetime of the lambda a call to the lambda after the object is destroyed has undefined behavior. 请注意,在该情况下,
this
被捕获你必须确保指针对象的生命周期包围拉姆达对象后拉姆达呼叫毁了未定义的行为的寿命。 The more simple case that captures a copy of a
is completely self-contained and has no such lifetime issues. 捕获的副本更简单的情况下,
a
完全独立的,没有这样的寿命问题。
You capture class members by saying this
in the capture list. 您可以通过在捕获列表中说明
this
来捕获类成员。 This has nothing to do with the fact that the member is const
. 这与成员是
const
的事实无关。
Example: 例:
#include <iostream>
struct Foo
{
const int a = 0;
int b;
Foo() : b{42} {
auto f = [this]() { std::cout << a << " " << b << std::endl; };
// ^^^^
f();
}
};
int main() {
Foo x;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.