Home >Backend Development >C++ >When and Why Use the `mutable` Keyword in C 11 Lambdas with Capture-by-Value?

When and Why Use the `mutable` Keyword in C 11 Lambdas with Capture-by-Value?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 01:07:14989browse

When and Why Use the `mutable` Keyword in C  11 Lambdas with Capture-by-Value?

Mutable Keyword in C 11 Lambdas for Capture-by-Value

Capture-by-value in C 11 lambdas allows the lambda to capture a variable from its scope by making a copy. However, by default, this copy is marked as immutable, meaning the lambda cannot modify it.

Rationale for Mutability

The reason for this default behavior stems from the fundamental principle of function objects: they should produce the same result every time they are called. If a lambda could modify a captured variable, it would violate this principle.

By using the mutable keyword, the programmer explicitly declares that the lambda can modify the captured variable. This relaxation is necessary because capture-by-value was designed to allow lambda users to change the captured temporary. In this case, it makes sense to allow modification under the programmer's control.

Example

Consider the code snippet you provided:

// ...
// [=](){n = 10;}();          // Error: a by-value capture cannot be modified in a non-mutable lambda

This code will throw an error because the lambda is capturing n by value and attempting to modify it without using the mutable keyword. To make this code valid, use mutable:

// ...
[=]() mutable {n = 10;}();

Conclusion

The mutable keyword in C 11 lambdas for capture-by-value serves as a reminder that function objects should generally produce consistent results. When it is necessary to modify a captured variable, the mutable keyword explicitly allows it. By understanding this rationale, programmers can use lambdas effectively and avoid potential errors.

The above is the detailed content of When and Why Use the `mutable` Keyword in C 11 Lambdas with Capture-by-Value?. 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