This is really bugging me, coming from a C# background.
Sometimes, I see functions written like this:
int computeResult();
This is what I'm used to. But then I see them written like this:
void computeResult(int &result);
I find this strange. What benefits does the second method have over the first, if any? There must be something, since I see it all the time.
The major advantage of return by address over return by reference is that we can have the function return nullptr if there is no valid object to return.
The major use of references is that it acts as function formal parameters for supporting pass-by-reference. In reference, a variable passes into a function. After that, the function works on the original copy and not a clone copy is pass-by-value.
The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable. Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.
A return value is a result of the function's execution. It can be returned to the block of code that called the function, and then used as needed. Parameters are the necessary input for a function to be executed and produce a result. Parameters are variables defined by name.
There are two common reasons for such non-const reference parameters:
You may need multiple "out" parameters in a function, and using reference parameter(s) allows for this.
Your object may be expensive to copy, and so you pass in a reference that will be mutated rather than returning an object that may get copied as part of the return process. Expensive-to-copy objects may include standard containers (like vector
) and objects that manage heap memory where an allocation-copy-deallocate sequence would occur. Note that compilers are getting really good at optimizing away these copies when possible and so this reason has less import than it used to.
EDIT: I should clarify that even in C++ the specific example you've provided with a single builtin type reference parameter is pretty atypical. In such cases a return value is almost always preferred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With