Home  >  Article  >  Backend Development  >  Is Capturing a Reference by Reference in a C 11 Lambda Safe?

Is Capturing a Reference by Reference in a C 11 Lambda Safe?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 03:50:02274browse

 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&amp; x) {
    return [&amp;]{ 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!

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