Returning vs. using a reference parameter

前端 未结 1 1004
遇见更好的自我
遇见更好的自我 2020-12-30 02:28

This is really bugging me, coming from a C# background.

Sometimes, I see functions written like this:

int computeResult();

This is

相关标签:
1条回答
  • 2020-12-30 03:12

    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.

    0 讨论(0)
提交回复
热议问题