문제

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