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

后端 未结 2 1093
温柔的废话
温柔的废话 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:28

    The reasoning is not correct because boo returns a temporary object by value. Binding this temporary object to a reference implies that the lifetime of the temporary is extended. Standard quote (§ 12.2/5):

    […] 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 […]

    The reasoning would be correct if boo returned a reference. An example for an expression returning a reference to a temporary is string("a") += string("b"); using this value in a range-based for loop gives rise to undefined behavior.

提交回复
热议问题