0
#include<iostream>
using namespace std;

struct A{
    
    int x;
    int y;
    
    A(){
        
    }
    
    A(int a, int b){
        x = a;
        y = b;
    }
};

ostream& operator << (ostream& COUT, A& a){
    COUT<<a.x<<' '<<a.y<<endl;
    return COUT;
}

A operator + (A& a, A& b){
   A temp;
   temp.x = a.x + b.x;
   temp.y = a.y + b.y;
   return temp;
}

int main(){
    A a(12, 15);
    A b(20, 23);
    cout<<a<<b;
    A result = a + b;
    cout<<result;
    return 0;
} 

In this code, if instead of using A operator + (A& a, A& b), I return by reference, it shows an error. Can anyone let me know why can't I return a local variable by reference thank you.

  • Local variables (with automatic storage duration) are destructed at the end of function execution. What would you do with a reference to something that has been destructed previously? – Daniel Langr Feb 23 '22 at 13:03
  • 1
    What do you think it means for a variable to be local? – Scott Hunter Feb 23 '22 at 13:03
  • 3
    Compare 1) attaching a file to an email to 2) uploading the file to an online repository, sending its URL in the email, and deleting the file in the repo. – chi Feb 23 '22 at 13:05
  • 2
    [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Passerby Feb 23 '22 at 13:06
  • 2
    The object ceases to exist when the function returns. What sensible thing could you do with an object that doesn't exist? – molbdnilo Feb 23 '22 at 13:13
  • The object `temp` has its lifetime end when the `A& operator + (A& a, A& b)` function ends. Returning a reference to `temp` does not extend its lifetime beyond the function. This is a dangling reference. The reference you return references an object that does not exist after the function ends. @chi has a great analogy this is case #2. – drescherjm Feb 23 '22 at 13:15
  • Related: [https://stackoverflow.com/questions/46011510/what-is-a-dangling-reference](https://stackoverflow.com/questions/46011510/what-is-a-dangling-reference) – drescherjm Feb 23 '22 at 13:19
  • You can return a local **automatic** variable by reference (as you are suggest doing in the code example); but you cannot access it (can't do `A result = a + b;`) because will have already been destructed and the returned reference is a *dangling reference*. You can return a local **static** variable by reference, `static A temp;`. Either of those are bad use cases of a returning by reference. C++ allows you to do "bad things", because C++ is not a nanny language. It presumes the programmers knows what they're doing. – Eljay Feb 23 '22 at 13:54

1 Answers1

1

Local variables are typically stored in a stack frame and hence references point to a location in the stack and the values may very likely be overwritten by the next call.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51