Home > Backend Development > C++ > body text

How to Capture by Value and Modify Captured Variables in C Lambda Expressions?

Linda Hamilton
Release: 2024-11-03 11:12:29
Original
595 people have browsed it

How to Capture by Value and Modify Captured Variables in C   Lambda Expressions?

Lambda Capture and Constness in C 0x

A common question arises when working with lambda expressions in C 0x: is there a way to capture by value and at the same time prevent the captured value from being made const?

The C language standard specifies that lambda expressions that capture variables by value do so in a const manner. This means that the captured value cannot be modified inside the lambda. However, in certain scenarios, it may be necessary to capture a variable by value but still modify its value.

For example, consider a library functor with a non-const operator() method that we want to capture and call in a lambda. The following code will not compile:

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

int main()
{
  foo afoo;

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

  return 0;
}</code>
Copy after login

The error here is that the lambda expression's operator() is declared as const due to the surrounding [=] capture list. To fix this, we can use the mutable keyword. By adding mutable to the lambda capture list, we allow the lambda to modify captured variables, even those captured by value:

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

This modification makes the lambda's operator() not const, allowing us to call the non-const operator() of the afoo object.

Therefore, to capture by value in a lambda expression and prevent the captured value from being const, use the mutable keyword in the capture list. This allows the lambda to modify the captured variable without causing compilation errors.

The above is the detailed content of How to Capture by Value and Modify Captured Variables in C Lambda Expressions?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template