简体   繁体   English

为什么我不能更改由 lambda 函数中的副本捕获的变量的值?

[英]Why can't I change the value of a variable captured by copy in a lambda function?

I'm reading the C++ Programming Language by B. Stroustrup in its section 11.4.3.4 "mutable Lambdas", which says the following:我正在阅读 B. Stroustrup 的 C++ Programming Language 在其第 11.4.3.4 节“可变 Lambdas”中的内容,其中说:

Usually, we don't want to modify the state of the function object (the closure), so by default we can't.通常,我们不想修改函数对象(闭包)的状态,所以默认情况下我们不能。 That is, the operator()() for the generated function object (§11.4.1) is a const member function.也就是说,生成的函数对象(第 11.4.1 节)的operator()() ) 是一个const成员函数。 In the unlikely event that we want to modify the state (as opposed to modifying the state of some variable captured by reference; §11.4.3), we can declare the lambda mutable .万一我们想要修改状态(而不是修改通过引用捕获的某些变量的状态;第 11.4.3 节),我们可以声明 lambda mutable

I don't understand why the default for the operator()() is const when the variable is captured by value.我不明白为什么在按值捕获变量时operator()()的默认值是const What's the rational for this?这有什么道理? What could go wrong when I change the value of a variable, which is copied into the function object?当我更改复制到函数对象中的变量的值时会出现什么问题?

One can think of lambdas as classes with operator()() , which by default is defined as const .可以将 lambda 视为带有operator()() ,默认情况下,其定义为const That is, it cannot change the state of the object.也就是说,它不能改变对象的状态。 Consequently, the lambda will behave as a regular function and produce the same result every time it is called.因此,lambda 将作为一个常规函数运行并在每次调用时产生相同的结果。 If instead, we declare the lambda as mutable, it is possible for the lambda to modify the internal state of the object, and provide a different result for different calls depending on that state.相反,如果我们将 lambda 声明为可变的,则 lambda 可能会修改对象的内部状态,并根据该状态为不同的调用提供不同的结果。 This is not very intuitive and therefore discouraged.这不是很直观,因此不鼓励。

For example, with mutable lambda, this can happen:例如,对于可变 lambda,这可能发生:

#include <iostream>

int main()
{
  int n = 0;
  auto lam = [=]() mutable {
    n += 1;
    return n;
  };

  std::cout << lam() << "\n";  // Prints 1
  std::cout << n << "\n";      // Prints 0
  std::cout << lam() << "\n";  // Prints 2
  std::cout << n << "\n";      // Prints 0
}

It is easier to reason about const data.更容易推理 const 数据。

By defaulting const, brief lamndas are easier to reason about.通过默认 const,简短的 lamndas 更容易推理。 If you want mutability you can ask for it.如果你想要可变性,你可以要求它。

Many function objects in std are copied around; std 中的许多函数对象都被复制了; const objects that are copied have simpler state to track.复制的 const 对象具有更简单的状态来跟踪。

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

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