this指针_如果需要捕捉this指针,明确地捕捉所有变量(不要使用隐式捕捉)

b30e59fade90d8938e738e8983fc479a.png

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(无论是明确地还是通过默认捕捉)指针,进行提示。

觉得本文有帮助?请分享给更多人。

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值