前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则F.54:不要隐式捕捉this指针

C++核心准则F.54:不要隐式捕捉this指针

作者头像
面向对象思考
修改2020-03-25 15:50:33
3320
修改2020-03-25 15:50:33
举报

F.54: If you capture this, capture all variables explicitly (no default capture)

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

译者注:隐式捕捉是指在捕捉列表中忽略变量名,只是依靠使用和lamda表达式外的变量同样的名称来实现的捕捉。例如否面示例代码中的:

代码语言:javascript
复制
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(示例)
代码语言:javascript
复制
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(无论是明确地还是通过默认捕捉)指针,进行提示。

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

关注【面向对象思考】,每天前进一小步

有任何疑问,欢迎留言提问或讨论


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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.54: If you capture this, capture all variables explicitly (no default capture)
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档