问题
In what situations it is preferred to return an object instead of just modifying an object passed to that function by reference? How do I know which one should I pick?
Actually, the question is if there are things I wouldn't be able to do without the ability to return an object from function, but instead only modifying objects passed by reference.
回答1:
The main pragmatic difference between
TYPE function () ;
and
void function (TYPE &value) ;
is that the former can be used in expressions.
a = 10 * function () ;
if (function ()) { }
That is the main design consideration.
Beyond that, I would have to get into opinion. I am going to stick to the objective difference.
回答2:
Its very simple...
Return by "value": - If you want a copy of the object with the current state of the object; - And inst important if the state of the original object change latter;
Return by reference: - If you want to have the correct state when the object is updated by others; - If you want to change the state of the object, and others be aware of that changes;
Those are the most important reasons.
But exist a special use case that you must be aware:
By techinical reasons, the current languages normally are faster when you return by reference. If speed is a requirement you should also consider this constraint to take the best decision.
But the fundamental decision is about how you want to deal with the state of the object.
回答3:
Returning something is the easy option but you'll use the reference if something speaks against it. One reason is because you have something else in mind for the return value, like a success/failure code. Another is because it would look big on the stack and you're on a tiny computer. Then, of course, you might want to modify an existing variable or structure instead of making a new one. I think that's it.
I'm not aware of anything you can't do by passing a reference or pointer to receive the result.
来源:https://stackoverflow.com/questions/26193575/function-returning-value-vs-modifying-value-passed-by-reference