Why do compilers give a warning about returning a reference to a local stack variable if it is undefined behaviour?

前端 未结 7 2127
温柔的废话
温柔的废话 2021-01-01 12:13

The C++ standard states that returning reference to a local variable (on the stack) is undefined behaviour, so why do many (if not all) of the current compilers only

相关标签:
7条回答
  • 2021-01-01 12:50

    It's pretty much super-bad practice to rely on this, but I do believe that in many cases (and that's never a good wager), that memory reference would still be valid if no functions are called between the time foo() returns and the time the calling function uses its return value. In that case, that area of the stack would not have an opportunity to get overwritten.

    In C and C++ you can choose to access arbitrary sections of memory anyway (within the process's memory space, of course) via pointer arithmetic, so why not allow the possibility of constructing a reference to wherever one so chooses?

    0 讨论(0)
提交回复
热议问题