Search code examples
c++pass-by-referencepass-by-value

Is passing by reference then copying and passing by value functionally different?


Is there a functional difference between:

void foo(const Bar& bar) {
  Bar bar_copy(bar);
  // Do stuff with bar_copy
}

and

void foo(Bar bar) {
  // Do stuff with bar
}

Solution

  • Yes, there is a valuable difference.

    void foo(Bar bar) can copy-construct or move-construct bar, depending on the calling context.

    And when a temporary is passed to foo(Bar bar), your compiler may be able to construct that temporary directly where bar is expected to be. Hat tip to template boy.

    Your function void foo(const Bar& bar) always performs a copy.

    Your function void foo(Bar bar) may perform a copy or a move or possibly neither.