Home >Backend Development >C++ >Is Lambda Capture by Value Always Constant in C 0x?

Is Lambda Capture by Value Always Constant in C 0x?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 19:42:30297browse

Is Lambda Capture by Value Always Constant in C  0x?

Lambda Capture by Value Always Constant in C 0x?

This issue arises when attempting to capture a value by reference but modify its contents within a lambda expression. The compiler treats captured values as constants by default, ensuring they remain unchanged. However, some scenarios may require non-const access to captured values.

Understanding Capture by Value:
In C 0x, lambda functions can capture variables by value or by reference. When capturing by value, a copy of the variable is created within the lambda's scope, allowing modification within the lambda. However, by default, captured copies are treated as constant, preventing their modification.

Mutable Keyword to the Rescue:
To overcome this limitation, the mutable keyword can be employed. By prepending mutable to the parameter list of a lambda, we explicitly declare the captured value as modifiable within the lambda's scope. This enables non-const access to the captured value, resolving the issue described in the provided code snippet.

Example:
Consider the following code that attempts to capture a value by reference and call a non-const method:

struct foo
{
bool operator () ( const bool & a )
{

return a;

}
};

int main()
{
foo afoo;

auto bar = [=] () -> bool

{
  afoo(true);
};

return 0;
}

In this code, making foo::operator() const resolves the compilation issue. However, using mutable directly within the lambda expression provides greater flexibility and enables non-const access to the captured value without modifying the original declar

The above is the detailed content of Is Lambda Capture by Value Always Constant 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