C++ problematic code piece

后端 未结 3 1574
孤城傲影
孤城傲影 2021-01-23 15:03

We got practice sheets for a test next week, for studying a little bit of C++ (still a beginner here). I still can\'t figure out a simple question.

That is, why are thes

3条回答
  •  花落未央
    2021-01-23 15:41

    The behavior of the returned value is undefined.The tricky thing here is that if you test your function with some kind of operation ( eg. printing to std output or assertion) you might often get an expected result but that doesn't mean it is safe since returned value is pointing to value written in the stack which could be wiped out at any given moment right after the function returns ( it is called stack unwinding). So, the rule of thumb is, don't return the address or reference to a locally defined variable of a function unless it was defined as static and why on earth would one prefer that unless situations force you? :-)

提交回复
热议问题