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

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

    Because standard does not restrict us.

    If you want to shoot to your own foot you can do it!

    However lets see and example where it can be useful:

    int &foo()
    {
        int y;
    }
    
    bool stack_grows_forward()
    {
        int &p=foo();
        int my_p;
        return &my_p < &p;
    }
    

提交回复
热议问题