Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

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";.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top