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

前端 未结 7 2156
温柔的废话
温柔的废话 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:35

    Compilers should not refuse to compile programs unless the standard says they are allowed to do so. Otherwise it would be much harder to port programs, since they might not compile with a different compiler, even though they comply with the standard.

    Consider the following function:

    int foobar() {
        int a=1,b=0;
        return a/b;
    }
    

    Any decent compiler will detect that I am dividing by zero, but it should not reject the code since I might actually want to trigger a SIG_FPE signal.

    As David Rodríguez has pointed out, there are some cases which are undecidable but there are also some which are not. Some new version of the standard might describe some cases where the compiler must/is allowed to reject programs. That would require the standard to be very specific about the static analysis which is to be performed.

    The Java standard actually specifies some rules for checking that non-void methods always return a value. Unfortunately I haven't read enough of the C++ standard to know what the compiler is allowed to do.

提交回复
热议问题