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

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

    It is almost impossible to verify from a compiler point of view whether you are returning a reference to a temporary. If the standard dictated that to be diagnosed as an error, writing a compiler would be almost impossible. Consider:

    bool not_so_random() { return true; }
    int& foo( int x ) {
       static int s = 10;
       int *p = &s;
       if ( !not_so_random() ) {
          p = &x;
       }
       return *p;
    }
    

    The above program is correct and safe to run, in our current implementation it is guaranteed that foo will return a reference to a static variable, which is safe. But from a compiler perspective (and with separate compilation in place, where the implementation of not_so_random() is not accessible, the compiler cannot know that the program is well-formed.

    This is a toy example, but you can imagine similar code, with different return paths, where p might refer to different long-lived objects in all paths that return *p.

提交回复
热议问题