Home > Backend Development > C++ > Why is the `mutable` Keyword Necessary for Capture-by-Value in C 11 Lambdas?

Why is the `mutable` Keyword Necessary for Capture-by-Value in C 11 Lambdas?

Mary-Kate Olsen
Release: 2024-12-07 00:04:11
Original
1009 people have browsed it

Why is the `mutable` Keyword Necessary for Capture-by-Value in C  11 Lambdas?

Exploring C 11 Lambda's Requirement for "mutable" in Capture-by-Value

In C 11, lambdas captured by value are functionally immutable, meaning they cannot modify the captured values by default. To amend this behavior, the "mutable" keyword is employed to allow modifications within the lambda's scope.

Consider the following example:

int main() {
    int n;
    [&]() { n = 10; }(); // OK, captures by reference

    [=]() mutable { n = 20; }(); // OK, captures by value with "mutable"

    // [=](){n = 10;}(); // Error, cannot modify by-value capture without "mutable"

    std::cout << n << "\n"; // Prints "10"
}
Copy after login

The question arises: Why is the "mutable" keyword necessary for capture-by-value?

Traditionally, parameters passed to named functions are implicitly mutable, allowing for modifications within the function. However, lambdas provide both capture-by-reference and capture-by-value mechanisms, which introduce distinct behavior.

By default, capture-by-value creates a copy of the external variable, and the lambda may only operate on this temporary value. Without "mutable," any attempt to modify the captured value will result in a compiler error, as it violates the principle of immutability for function objects.

Therefore, the "mutable" keyword is introduced to explicitly allow modifications within a lambda that captures by value. It signals to the compiler that the captured copy can be treated as mutable, thus returning to a more traditional function-like behavior.

In summary, the "mutable" keyword is required for capture-by-value in C 11 lambdas because it ensures that the function object's output remains consistent with its inputs, while allowing for modifications to the captured copy within the lambda's scope.

The above is the detailed content of Why is the `mutable` Keyword Necessary for Capture-by-Value in C 11 Lambdas?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template