Home >Backend Development >C++ >Why Is the `mutable` Keyword Necessary for Modifying Captured Variables in C 11 Lambdas?

Why Is the `mutable` Keyword Necessary for Modifying Captured Variables in C 11 Lambdas?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 11:10:14720browse

Why Is the `mutable` Keyword Necessary for Modifying Captured Variables in C  11 Lambdas?

Understanding the Need for "Mutable" in C 11 Lambda Capture-by-Value

Lambda expressions in C 11 offer two capture modes: capture-by-reference and capture-by-value. When capturing variables by value, the lambda can modify them. However, this behavior is not automatic. The "mutable" keyword is required to allow modification.

Rationale Behind the "Mutable" Requirement

One key difference between lambdas and traditional named functions is that lambdas are designed to encapsulate a set of operations that operate on a local, temporary state. By default, this state should remain constant throughout the lambda's execution.

By allowing modification of capture-by-value variables without "mutable," lambdas would violate the principle of function determinism. A lambda should produce the same output every time it's called, regardless of the state of the surrounding code. Modifying capture-by-value variables introduces non-determinism, making the lambda's behavior difficult to predict.

Understanding Capture-by-Value

Capture-by-value is designed to create a local copy of the captured variables. This copy is intended to be immutable, ensuring that the lambda's behavior remains consistent. However, there may be situations where the lambda needs to change the copy of the captured variable.

For example, consider the following code:

int main() {
    int n;
    [&](){n = 10;}();             // OK
    [=]() mutable {n = 20;}();    // OK
    // [=](){n = 10;}();          // Error: a by-value capture cannot be modified in a non-mutable lambda
    std::cout << n << "\n";       // "10"
}

Without "mutable," the lambda capture-by-value cannot modify the copy of "n." This ensures that the output remains consistent, even though the lambda's execution modifies the original "n" variable.

By using "mutable," we explicitly indicate that the lambda is allowed to modify the captured copy. This allows us to change the copy of "n" in the lambda without affecting the behavior of the enclosing function.

The above is the detailed content of Why Is the `mutable` Keyword Necessary for Modifying Captured Variables in C 11 Lambdas?. 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