C ++ Lambda捕获此vs通过引用捕获 [英] C++ lambda capture this vs capture by reference

查看:60
本文介绍了C ++ Lambda捕获此vs通过引用捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要生成一个调用成员函数的lambda,我应该通过引用捕获还是捕获 this?我的理解是,&仅捕获使用的变量,而 this则捕获所有成员变量。所以最好使用'&'?

If I need to generate a lambda that calls a member function, should I capture by reference or capture 'this'? My understanding is that '&' captures only the variables used, but 'this' captures all member variable. So better to use '&'?

class MyClass {
  public:
    int mFunc() {
      // accesses member variables
    }

    std::function<int()> get() {
      //return [this] () { return this->mFunc(); };
      //  or
      //return [&] () { return this->mFunc(); };
    }

  private:
    // member variables
}


推荐答案

对于您提供的特定示例,您想要的是通过 this 捕获。从概念上讲,通过引用捕获 this this ,您只能将其用作访问类成员或获取类实例地址的指针。在lambda函数内部,如果您访问隐式使用 this 指针的内容(例如,调用成员函数或访问成员变量而未显式使用 this ),编译器将其视为您一直使用 this 。您也可以列出多个捕获,因此,如果要捕获成员和局部变量,则可以独立选择是按引用还是按值捕获它们。以下文章应使您在lambda和捕获方面有良好的基础:

For the specific example you've provided, capturing by this is what you want. Conceptually, capturing this by reference doesn't make a whole lot of sense, since you can't change the value of this, you can only use it as a pointer to access members of the class or to get the address of the class instance. Inside your lambda function, if you access things which implicitly use the this pointer (e.g. you call a member function or access a member variable without explicitly using this), the compiler treats it as though you had used this anyway. You can list multiple captures too, so if you want to capture both members and local variables, you can choose independently whether to capture them by reference or by value. The following article should give you a good grounding in lambdas and captures:

https://crascit.com/2015/03/01/lambdas-for-lunch/

另外,您的示例使用 std :: function 作为返回类型,lambda通过该返回类型传递回调用方。请注意, std :: function 并不总是像您想象的那样便宜,因此,如果您能够直接使用lambda,而不必将其包装在 std :: function ,它可能会更有效。以下文章虽然与您的原始问题没有直接关系,但仍可能为您提供一些有关lambda和 std :: function 的有用材料(请参见替代方法部分一种存储功能对象的方式,但总的来说可能是有趣的文章):

Also, your example uses std::function as the return type through which the lambda is passed back to the caller. Be aware that std::function isn't always as cheap as you may think, so if you are able to use a lambda directly rather than having to wrap it in a std::function, it will likely be more efficient. The following article, while not directly related to your original question, may still give you some useful material relating to lambdas and std::function (see the section An alternative way to store the function object, but the article in general may be of interest):

https://crascit.com/2015/06/03/on-leaving-scope-part-2/

这篇关于C ++ Lambda捕获此vs通过引用捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆