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;
}
有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top