Link to Lambda reference variable by reference

For lambda, I would like to grab something from a link that has already been held in the external area by link. Suppose the reference value highlights lambda, but not the area in which lamdba is created.

I know that if lambda commits the reference variable by value, the reference object will be copied. I would like to avoid this copy.

But what happens if I get a reference variable by reference? What if the original reference variable goes out of scope before lambda execution? It is safe? In other words: is the object a reference a reference or is it a reference variable specified in lambda?

auto f() {
    const auto & myRef = g();
    return [&]{ myRef.doSomething(); };
}

f()();  // Safe?
+4
source share
1 answer

Yes, the key problem when capturing an object by reference is the lifetime of the reference object, and not the lifetime of any intermediate links used to obtain it. You can treat the link as an alias, not an actual variable. (And in the type system, links are handled differently than regular variables.) The link refers to the source object and is independent of other aliases used for the object's alias (except that they have the same object).

===== ===== EDIT

SO ( dyp), , . " " , , , , , -, - , , . ( , SO, , , , , .)

, ++ 14/17, , , . , , ++ 14/17 -, , , . (, - , , UB, .)

, .

+4

Source: https://habr.com/ru/post/1536487/


All Articles