Home > Backend Development > C++ > body text

Can C 0x Lambda Captures Be Modified Without Being Const?

DDD
Release: 2024-10-30 13:28:01
Original
823 people have browsed it

Can C  0x Lambda Captures Be Modified Without Being Const?

Can C 0x Lambda Captures Be Modified without Being Const?

Lambda captures in C 0x typically capture variables by reference, which are inherently constant. However, certain scenarios require the modification of captured variables, raising the question, "Can captured values be made non-const?"

Consider a library functor, foo, with a non-const method, operator(), that needs to be called within a lambda. The code snippet below attempts this but fails to compile:

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

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

The compilation error arises because the lambda's operator() is implicitly marked as const due to the captured values being constant. To resolve this issue, C 0x provides the mutable keyword.

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

By adding mutable, the lambda's operator() is no longer const, allowing the captured variables to be modified within the lambda. This enables the modification of library functors or other non-const captured values as needed within lambdas.

The above is the detailed content of Can C 0x Lambda Captures Be Modified Without Being Const?. 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!