0

I know it's bad to return reference to a local object; i.e., below is bad:

int& Obj::func(){
   int a = 1;
   return a;
}

But how about returning a local variable that itself is a reference? For example:

int& Obj::func(){
    int& a = anotherFunc();
    return a;
}

Here, anotherFunc() is itself returning int& that ultimately comes from a vector field in Obj, such as:

int& Obj::anotherFunc(){
    return vec[2]; // here vec is defined in class Obj
}

I think it's fine because reference are treated the same way as pointers, but I didn't find any articulation on this point in my C++ books.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Where is `vec` declared? You have to be careful to avoid undefined behavior if the program reaches the end of the lifetime of the referenced object. – Code-Apprentice Nov 29 '21 at 22:11
  • It's the ***to*** part of "reference to local object" that's the problem. If the reference is not to a local object, this, of course, does not apply. – Sam Varshavchik Nov 29 '21 at 22:13
  • @Code-Apprentice "*here anotherFunc() is itself returning int& that ultimately comes from a vector field in Obj*" – scohe001 Nov 29 '21 at 22:14
  • Instead of thinking of these practices as "bad" or "good", consider object lifetime in all of these cases. That is what matters. You can return a reference if the object still exists after the return. – Drew Dormann Nov 29 '21 at 22:14
  • There is another issue with _"returning a local variable that itself is a reference"_. A const reference or r-value reference can be bound to a temporary, extending the temporary's lifetime **only** to the lifetime of that variable. – Drew Dormann Nov 29 '21 at 22:21
  • 1
    There is nothing wrong in returning a reference if it refers to a valid `int` that continues to exist. Having multiple steps of returning the reference or using it to initialise other references does not change that. Behaviour is undefined if `vec[2]` ceases to exist when `Obj::anotherFunc()` returns or when `Obj::func()` returns. Behaviour is also undefined if `vec[2]` ceases to exist (i.e. the returned reference becomes a dangling reference) after `Obj::func()` returns and before the reference is used by the caller. – Peter Nov 30 '21 at 01:05
  • 2
    The answer is a combination of [Reference to a reference in c++](https://stackoverflow.com/questions/16480984/) (supporting your "I think it's fine" point) and [A: Is the practice of returning a C++ reference variable evil?](https://stackoverflow.com/a/753368/) (covering why it's OK for a member function to return a reference to member data -- I linked to a specific answer because the current top-voted answer starts with a situation not relevant here). It doesn't seem like either of them count as a duplicate, though. *(If those aren't enough, I might get time to write an answer later.)* – JaMiT Nov 30 '21 at 02:46

0 Answers0