Return passed reference to object

113 views Asked by At

I know that we can't return a local variable by reference since it would go out of scope. I am a bit confused when it comes to returning passed references though. For instance is the below example legal or would it lead to undefined behaviour?

classobject &function(classobject &obj) {
 return obj;
}
2

There are 2 answers

0
AudioBubble On BEST ANSWER

That's absolutely fine, and in fact it's very often how non-member operator<< and the like are implemented, to allow you to chain the operator.

The key thing to think about is object lifetime, and as you know the object is passed in by reference, it has to outlive the function call. This makes it safe to return the same reference.

1
Ragnar On

This is legal and is used for example by cout<< (although the argument is *this instead of an explicit function argument). It returns a reference to cout, allowing cout<<"a"<<"b";.