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

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

    If you return a pointer/reference to a local inside function the behavior is well defined as long as you do not dereference the pointer/reference returned from the function.

    It is an Undefined Behavior only when one derefers the returned pointer.

    Whether it is a Undefined Behavior or not depends on the code calling the function and not the function itself.

    So just while compiling the function, the compiler cannot determine if the behavior is Undefined or Well Defined. The best it can do is to warn you of a potential problem and it does!

    An Code Sample:

    #include 
    
    struct A
    { 
       int m_i;
       A():m_i(10)
       {
    
       } 
    };  
    A& foo() 
    {     
        A a;
        a.m_i = 20;     
        return a; 
    } 
    
    int main()
    {
       foo(); //This is not an Undefined Behavior, return value was never used.
    
       A ref = foo(); //Still not an Undefined Behavior, return value not yet used.
    
       std::cout<

    Reference to the C++ Standard:
    section 3.8

    Before the lifetime of an object has started but after the storage which the object will occupy has been allo-cated 34) or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways. Such a pointer refers to allocated storage (3.7.3.2), and using the pointer as if the pointer were of type void*, is well-defined. Such a pointer may be dereferenced but the resulting lvalue may only be used in limited ways, as described below. If the object will be or was of a class type with a non-trivial destructor, and the pointer is used as the operand of a delete-expression, the program has undefined behavior. If the object will be or was of a non-POD class type, the program has undefined behavior if:

    — .......

提交回复
热议问题