why not crash after the temporary object is destroyed

前端 未结 4 1749
礼貌的吻别
礼貌的吻别 2021-01-14 03:26
class C
{
public:
    int True(int i) const
    {
        return i+2;
    }
};


const C& F(const C& c)
{
    return c;
}

int main()
{ 
    const C& c =         


        
4条回答
  •  囚心锁ツ
    2021-01-14 04:12

    Paragraph 12.2/4 of the C++11 Standard specifies that in some situations the lifetime of temporaries can indeed be extended beyond the end of the full expression in which they are generated:

    There are two contexts in which temporaries are destroyed at a different point than the end of the full expression. [...]

    The first context is not relevant. However, per Paragraph 12.2/5:

    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:

    — A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

    A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.

    — The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

    — A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.

    Here, the temporary constructed with C() is bound to the argument c of function F. Therefore, the temporary is destroyed at the end of the full-expression which contains the call to function F(), and the returned reference is dangling.

    Invoking function True() on it causes Undefined Behavior.

提交回复
热议问题