Home >Backend Development >C++ >Is Capturing a Reference by Reference in a C 11 Lambda Safe?
Capturing a Reference by Reference in a C 11 Lambda
In C 11, we often use lambdas to capture variables from the surrounding context. But what happens when we capture a reference by reference? Is it safe to do so?
Problem Details
Consider the following code:
<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>
In this code, we have a lambda that captures a reference to the integer variable i. We then modify i in the main function and call the lambda. The question is, will the lambda output 3 or 5?
Standard-Based Answer
The code is guaranteed to output 5, without invoking undefined behavior.
Explanation
According to the C 11 standard ([expr.prim.lambda]/17), only id-expressions referring to entities captured by copy are transformed into a member access on the lambda closure type. Id-expressions referring to entities captured by reference are left alone and still denote the same entity they would have denoted in the enclosing scope.
This means that the reference x in the lambda is not changed. It still refers to the same integer variable i in the main function. Therefore, when we modify i in the main function, the lambda will still see the modified value.
The above is the detailed content of Is Capturing a Reference by Reference in a C 11 Lambda Safe?. For more information, please follow other related articles on the PHP Chinese website!