![b30e59fade90d8938e738e8983fc479a.png](https://i-blog.csdnimg.cn/blog_migrate/cfb0c5eec12ea2630620c4bf8ce116c1.jpeg)
F.54: If you capture this, capture all variables explicitly (no default capture)
F.54:如果需要捕捉this指针,明确地捕捉所有变量(不要使用隐式捕捉)。
译者注:隐式捕捉是指在捕捉列表中忽略变量名,只是依靠使用和lamda表达式外的变量同样的名称来实现的捕捉。例如否面示例代码中的:
auto lambda = [=]{ use(i, x); };
Reason(原因)
It's confusing. Writing [=] in a member function appears to capture by value, but actually captures data members by reference because it actually captures the invisible this pointer by value. If you meant to do that, write this explicitly.
这种做法难于理解。在成员函数中的捕捉列表[=]看起来是值捕捉,但是由于实际以值方式捕捉了不可见的this指针,因而实际上是通过引用方式捕捉数据成员。如果你就是想这样做,明确地将this写入捕捉列表。
Example(示例)
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(0, 42); x = 43; lambda(); // calls use(0, 43); // ... auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing // ... }};
Note(注意)
This is under active discussion in standardization, and may be addressed in a future version of the standard by adding a new capture mode or possibly adjusting the meaning of [=]. For now, just be explicit.
这是一个在标准化过程中不太活跃的议题,可能在被将来版本的标准以增加一种新的捕捉方法或者修改[=]含义的方式解决。目前,只要明确就好。
Enforcement(实施建议)
- Flag any lambda capture-list that specifies a default capture and also captures this (whether explicitly or via default capture)如果任何lambda表达式的捕捉列表被定义为隐式捕捉并同时捕捉this(无论是明确地还是通过默认捕捉)指针,进行提示。
觉得本文有帮助?请分享给更多人。
更多更新文章,欢迎关注微信公众号【面向对象思考】
面向对象设计,面向对象编程,面向对象思考!