Home  >  Article  >  Backend Development  >  Can Lambda Functions Capture Non-Const Values in C 0x?

Can Lambda Functions Capture Non-Const Values in C 0x?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 06:57:29686browse

Can Lambda Functions Capture Non-Const Values in C  0x?

Lambda Capture and Modifiable Captured Value

In C 0x, lambda expressions offer a powerful means to capture local variables. However, by default, variables captured by value are treated as const. This can pose limitations when working with libraries that require modifying the captured value.

Consider the following scenario:

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

int main()
{
  foo afoo;

  // Attempt to capture non-const reference by value
  auto bar = [=]() -> bool { afoo(true); };
}</code>

This code fails to compile due to an attempt to modify the captured value afoo within the non-const member function afoo::operator().

Solution: Using Mutable Lambda

To capture by value while preserving the ability to modify the captured variable, one can employ the mutable keyword. By declaring the lambda as mutable, it allows the modification of its internal state, including captured values.

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

In this modified example, the lambda's operator() is allowed to modify the captured afoo, resolving the compilation error. Note that without the mutable keyword, the lambda would be considered const due to its captured non-const value.

The above is the detailed content of Can Lambda Functions Capture Non-Const Values in C 0x?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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