Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning vs. using a reference parameter [duplicate]

Tags:

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.

like image 576
jmegaffin Avatar asked Aug 23 '12 01:08

jmegaffin


People also ask

What is the advantage of returning a reference from the function?

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.

What is the advantage of reference parameter?

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.

What is the difference between return by value and reference?

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.

What is the difference between parameters and returned values?

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.


1 Answers

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.

like image 64
Mark B Avatar answered Nov 06 '22 10:11

Mark B