c++ - Lambda capture reference variable by reference -


for lambda, i'd capture reference held in outer scope reference already. assume referenced value outlives lambda, not scope in lamdba gets created.

i know that if lambda captures reference variable by value, referenced object copied. i'd avoid copy.

but happens if capture reference variable by reference? if original reference variable out of scope before executing lambda? safe? in other words: object behind reference referenced or reference variable referenced in lambda?

auto f() {     const auto & myref = g();     return [&]{ myref.dosomething(); }; }  f()();  // safe? 

yes, key issue in capturing object reference lifetime of referenced object, not lifetime of intervening references used it. can think of reference alias rather actual variable. (and in type system, references treated differently regular variables.) reference aliases original object, , independent of other aliases used alias object (other fact alias same object).

=====edit=====

according answer given this question (pointed out dyp), appears may not entirely clear. throughout rest of language, concept of "reference reference" doesn't make sense , reference created reference becomes peer of reference, apparently standard ambiguous case , lambda-captured references may in sense secondary, dependent on stack frame captured. (the explicit verbiage answer quotes calls out referenced entity, on face indicate usage safe long original object lives, binding mechanism may implicate capture chain being significant.)

i hope clarified in c++14/17, , prefer clarified guarantee legality usage. in particular, think c++14/17 ability capture variable via expression make more difficult capture scope via stack-frame pointer , sensible capture mechanism capture specific entities individually. (perhaps stack-frame-capture permitted if actual local object captured reference, since result in ub if lambda called outside scope in event.)

until clarification, may not portable.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -