Home > Backend Development > C++ > body text

How Can I Modify Captured Values in C 0x Lambdas When Capturing by Value?

DDD
Release: 2024-11-04 13:44:02
Original
715 people have browsed it

How Can I Modify Captured Values in C  0x Lambdas When Capturing by Value?

Lambda Capture by Value: Ensuring Non-Const Captured Values in C 0x

When capturing by value in C 0x lambda expressions, the captured values are automatically made constant. This can be an issue if you need to modify the captured values within the lambda.

For example, consider the following lambda that captures a struct foo by value:

<code class="cpp">struct foo {
  bool operator() (const bool &a) {
    return a;
  }
};

int main(int argc, char* argv[]) {
  foo afoo;

  auto bar = [=] () -> bool {
    afoo(true);
  };

  return 0;
}</code>
Copy after login

This code will not compile because the operator() method of foo is declared as const. To fix the issue, you can make the operator() method non-const:

<code class="cpp">struct foo {
  bool operator() (bool &a) {
    return a;
  }
};</code>
Copy after login

However, this is not always a desirable solution. In some cases, you may want to capture a value by value but still ensure that it is not modified within the lambda.

To achieve this, you can use the mutable keyword. By declaring the lambda as [=] () mutable -> bool, you allow the lambda to modify the captured values.

Example:

<code class="cpp">auto bar = [=] () mutable -> bool {
  afoo(true);
};</code>
Copy after login

In this example, the lambda can now modify the captured afoo object, even though it is captured by value.

The above is the detailed content of How Can I Modify Captured Values in C 0x Lambdas When Capturing by Value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!