C++11: The range-based for statement: “range-init” lifetime?

后端 未结 2 1089
温柔的废话
温柔的废话 2020-11-27 20:45

In the latest C++ standard it implies that:

for (foo : bar)
    baz;

is equivilant to:

{
    auto && r = bar;
    f         


        
2条回答
  •  清酒与你
    2020-11-27 21:29

    Is this reasoning correct? If not, why not?

    It is correct up until this point:

    And so the temporary return value of boo() is destroyed at the end of the statement "auto&&r=boo()" [...]

    Binding a temporary to a reference extends its lifetime to be that of the reference. So the temporary lasts for the whole loop (that's also why there is an extra set of {} around the whole construct: to correctly limit the lifetime of that temporary).

    This is according to paragraph 5 of §12.2 of the C++ standard:

    The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

    [various exceptions that don't apply here]

    This is an interesting property that allows abusing the ranged-for loop for non-rangey things: http://ideone.com/QAXNf

提交回复
热议问题