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.