简体   繁体   English

通过引用捕获C ++ Lambda

[英]C++ Lambda capture by reference

As far I know, after running the following code myString should have got the value "Inside lambda3.secondLambda". 据我所知,运行以下代码后,myString应该具有值“ Inside lambda3.secondLambda”。 Instead it will still have the value "Initialized". 相反,它将仍然具有“ Initialized”值。

std::string myString("Initialized");
auto lambda3 = [&]() { [&myString]() { myString = "Inside lambda3.secondLambda"; }; };

The first lambda captures all variables by reference and the sencond captures only myString by reference. 第一个lambda通过引用捕获所有变量,第二个lambda通过引用捕获仅myString。 Why does it not behave as I have expected? 为什么它的行为不符合我的预期?

By specifying the body of the lambda, you specify code that would be called when the lambda's operator() is called. 通过指定lambda的主体,可以指定调用lambda的operator()将调用的代码。

So you need to actually call the lambdas, otherwise it's simply code inside the definition of functions which never get called. 因此,您实际上需要调用lambda,否则,它只是函数定义内的代码,而这些代码永远不会被调用。 You can do: 你可以做:

auto lambda3 = [&] {
  auto l = [&myString] {
    myString = "Inside lambda3.secondLambda";
  };
  l();
};
lambda3();

To take it one step further, you can return the inner lambda and then execute it like this: 要更进一步,您可以返回内部lambda,然后像这样执行它:

auto lambda3 = [&] {
  return [&myString] {
    myString = "Inside lambda3.secondLambda";
  };
};
lambda3()();

You have defined a closure, but not actually run the function. 您已经定义了一个闭包,但实际上并未运行该函数。 You must actually run it like lambda3() if you want to execute its body. 如果要执行其主体,则实际上必须像lambda3()一样运行它。

However, you have nested lambdas, so you need to run what's in the lambda as well. 但是,您已经嵌套了lambda,因此您还需要运行lambda中的内容。 It's not clear why you are doing this. 目前尚不清楚为什么要这样做。 Your inner lambda is neither assigned inside the outer lambda's scope (so you can run it inside the lambda using the same syntax), or returned (so the caller of this lambda can run what it returns). 您的内部Lambda既没有在外部Lambda的范围内分配(因此您可以使用相同的语法在Lambda内运行它),也没有返回(因此该Lambda的调用者可以运行它返回的内容)。

If you returned it, you could do lambda3()() : 如果返回它,则可以执行lambda3()()

auto lambda3 = [&]() { return [&myString]() { myString = "Inside    
     lambda3.secondLambda"; }; };

Note: only the word return was added to allow lambda3()() to work. 注意:仅添加了单词return ,以允许lambda3()()工作。

In this particular example, you are better served with just: 在此特定示例中,最好仅提供以下服务:

auto lambda3 = [&myString]() { 
      myString = "Inside lambda3.secondLambda"; };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM