Home > Backend Development > C++ > body text

Does Capturing a Reference by Reference in C 11 Lambdas Guarantee Access to the Modified Value?

Mary-Kate Olsen
Release: 2024-11-03 22:39:03
Original
449 people have browsed it

Does Capturing a Reference by Reference in C  11 Lambdas Guarantee Access to the Modified Value?

Capturing a Reference by Reference in C 11 Lambdas

The Question:

Consider the following code snippet:

<code class="cpp">#include <functional>
#include <iostream>

std::function<void()> make_function(int&amp; x) {
    return [&amp;]{ std::cout << x << std::endl; };
}

int main() {
    int i = 3;
    auto f = make_function(i);
    i = 5;
    f();
}</code>
Copy after login

Can we guarantee that this program will output 5 without encountering undefined behavior? This question arises specifically when capturing the variable x by reference ([&]), and concerns whether capturing a reference to a variable will result in a dangling reference once the function make_function returns.

The Answer:

Yes, the code is guaranteed to work.

Explanation:

The C 11 lambda specification states that the reference captured here remains valid as long as the originally referenced object still exists. This means that even though the parameter x in make_function goes out of scope after the function returns, the lambda closure still retains a valid reference to the integer i.

Clarification:

To address some inaccuracies in previous responses:

  • "Scope" in C refers to a static, lexical region of code where unqualified name lookup associates a name with a declaration. It has no direct relation to lifetime.
  • "Reaching scope" rules for lambdas determine when capture is allowed based on syntactic rules, not lifetime.

In this specific case, the variable x is within the reaching scope of the lambda and is captured by reference. Therefore, the reference remains valid, and the lambda can continue to access the modified value of i.

Conclusion:

This code demonstrates the correct capture of a reference by reference in a lambda. It is guaranteed to output 5 without invoking undefined behavior.

The above is the detailed content of Does Capturing a Reference by Reference in C 11 Lambdas Guarantee Access to the Modified Value?. 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