C++: Reference to “out of scope” object

前端 未结 3 759
慢半拍i
慢半拍i 2020-12-20 18:33

There is one thing I never understood about references and I hope that one might help me. For all I know, a reference cannot be null. But what happens if you have a function

3条回答
  •  庸人自扰
    2020-12-20 18:41

    This causes undefined behaviour. Don't do it.

    Implementation-wise, realistically, the reference would point into the stack where the stackframe for the call to foo used to be. That memory will in many cases still make sense, so the error is often not immediately apparent. Therefore, you should take care never to make a dangling reference like that.

提交回复
热议问题