【问题标题】:Distinguish b/w captured `this` members from captured variables in C++ lambdas区分黑白捕获的“this”成员与 C++ lambda 中捕获的变量
【发布时间】:2017-10-18 21:01:17
【问题描述】:

我想知道 C++ 中 lambda 的捕获。 我知道 lambda 表达式只是某些仿函数类的“生成器”。 我想知道编译器如何区分捕获的“this”成员和生成的仿函数类的成员?

还有,第二个问题:

在下面的示例中a_ 来自捕获列表阴影A::a_。这种行为是否在标准中描述?我在任何地方都找不到答案。

class A {
    int a_ = 0;
public:
    void sth() {
        auto l = [this, a_=1](int a) { a_ = a; };
        l(1);
    }
};

【问题讨论】:

  • 这不会编译。 a_ 是不可变的,因为 lambda 未标记 mutable
  • @RichardHodges 我知道,这只是说明问题的示例

标签: c++ lambda


【解决方案1】:

分解(并修复错误):

class A {
    int a_ = 0;  // this is A::a_
public:
    void sth() {
        auto l = 
          [
              this,  // A::sth::lambda::l::_this 
              a_=a_   // A::sth::lambda::l::a_ = A::a_  // because the lambda's a_ does not exist until it's defined.
          ](int a) mutable 
          { 
              a_ = a;  // A::sth::lambda::l::a_ = argument a 
          };
        l(1);
    }
};

【讨论】:

  • 所以,如果我理解正确:当编译器在 lambda 主体中找到某个变量(此处为 a_)时,它会在主体中将其作为局部变量或作为传递的参数进行搜索,如果未找到则搜索此 var在 lambda 捕获 (lambda 'members') 中,如果没有这样的 lambda 成员,它会尝试获取 (A::sth::lambda::l::)_this->a_ ,对吗?这是定义的规则,是吗?
  • @J.Klimczak 在这种情况下,我们明确地捕获了 this(A's this)和 A's a_。我们将它们存储在 lambda 的 this 和 lambda 的 a 中。如果我们还在捕获块中指定了 &。在 lambda 的定义中引用代码中的变量时,首先搜索 lambda 的名称,然后是任何外部范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多