why not crash after the temporary object is destroyed

前端 未结 4 1752
礼貌的吻别
礼貌的吻别 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:03

    Normally, when a temporary is bound to a const reference, the lifetime of the temporary is extended to the lifetime of the reference. Thus if your code said const C& c = C() then the temporary would live as long as c does.

    However, you're passing the temporary to another function F(). In this case, §12.2.5 of the C++11 spec dictates that the temporary will persist until the completion of the full-expression containing the call.

    Therefore, when you say const C& c = F(C()), the temporary C() is actually destructed at the end of this statement, and is no longer valid on the next line.

    That said, your code appears to function properly because the call to c.True() is known at compile-time, and the function definition doesn't actually refer to any data in c, so the fact that the temporary is dead doesn't really affect the observed behavior. However this is technically undefined behavior.

提交回复
热议问题