why not crash after the temporary object is destroyed

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

    This invokes undefined behaviour. As soon as the full expression involving F(C()) completes, the temporary created by C() is destroyed, so the reference returned by F is no longer valid.

    However, undefined behaviour does not guarantee your program will crash. In more annoying cases (like this) it simply causes subtle, hard to diagnose bugs. As for why this undefined behaviour gives you this specific result, I refer you to this famous answer.

提交回复
热议问题