Why is returning a reference to a function local value not a compile error?

后端 未结 6 435
心在旅途
心在旅途 2020-12-16 09:39

The following code invokes undefined behaviour.

int& foo()
{
  int bar = 1234;
  return bar;
}

g++ issues a warning:

6条回答
  •  爱一瞬间的悲伤
    2020-12-16 09:57

    Something not mentioned by other answers yet is that this code is OK if the function is never called.

    The compiler isn't required to diagnose whether a function might ever be called or not. For example you might set up a program which looks for counterexamples to Fermat's Last Theorem, and calls this function if it finds one. It would be a mistake for the compiler to reject such a program.

提交回复
热议问题