【发布时间】:2017-08-24 06:45:32
【问题描述】:
看了这篇Cppcore Guideline F.54后有点困惑
关于 lambda 捕获
“在成员函数中写入 [=] 似乎是按值捕获,但 实际上通过引用捕获数据成员“
例子
class My_class {
int x = 0;
// ...
void f() {
int i = 0;
// ...
auto lambda = [=]{ use(i, x); }; // BAD: "looks like" copy/value capture
// [&] has identical semantics and copies the this pointer under the current rules
// [=,this] and [&,this] are not much better, and confusing
x = 42;
lambda(); // calls use(42);
x = 43;
lambda(); // calls use(43);
// ...
auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
// ...
}
};
为什么这被认为是不好的
auto lambda = [=]{ use(i, x); };
以下是一个很好的做法
auto lambda2 = [i, this]{ use(i, x); };
我尝试了这个例子,但没有发现任何区别。可能是我没有正确理解这些陈述
#include<iostream>
using namespace std;
class My_class {
public:
int x = 0;
// ...
void f() {
int i = 0;
// ...
auto lambda = [=]{ cout<<i<<x<<endl; }; // BAD: "looks like" copy/value capture
// [&] has identical semantics and copies the this pointer under the current rules
// [=,this] and [&,this] are not much better, and confusing
x = 42;
lambda(); // calls use(42);
x = 43;
lambda(); // calls use(43);
// ...
auto lambda2 = [i, this]{ cout<<i<<x<<endl; }; // ok, most explicit and least confusing
lambda2();
}
};
int main()
{
My_class val;
val.f();
}
输出
042
043
043
Program ended with exit code: 0
任何方向、指南或示例说明都会有所帮助
编辑
经过几次解释(见下面的答案) 创建了一个新示例来演示 行为
#include<iostream>
using namespace std;
class My_class {
public:
int x = 0;
// ...
void f() {
int i = 0;
// ...
auto lambda = [=]{ cout<<i<<x<<endl; x=10; }; // BAD: "looks like" copy/value capture
// [&] has identical semantics and copies the this pointer under the current rules
// [=,this] and [&,this] are not much better, and confusing
x = 42;
lambda(); // calls use(42);
cout<<"value of x is "<<x<<endl;
x = 43;
lambda(); // calls use(43);
// ...
auto lambda2 = [i, this]{ cout<<i<<x<<endl; }; // ok, most explicit and least confusing
lambda2();
}
};
int main()
{
My_class val;
val.f();
}
输出
042
value of x is 10
043
010
Program ended with exit code: 0
即使按值捕获,这也会改变外部 x 值
【问题讨论】: