Returning vs. using a reference parameter

jmegaffin picture jmegaffin · Aug 23, 2012 · Viewed 7.2k times · Source

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.

Answer

Mark B picture Mark B · Aug 23, 2012

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.