Home > Article > Backend Development > 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& x) { return [&]{ std::cout << x << std::endl; }; } int main() { int i = 3; auto f = make_function(i); i = 5; f(); }</code>
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:
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!