Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 425
wrhall Avatar asked Apr 02 '15 20:04

wrhall


People also ask

What is the difference between passing by reference and passing by value?

Basically, pass-by-value means that the actual value of the variable is passed and pass-by-reference means the memory location is passed where the value of the variable is stored.

Does passing by reference make a copy?

In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.

Does passing by reference change the value?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

What is passed by value and passed by reference in functions?

"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.


1 Answers

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.

like image 170
Drew Dormann Avatar answered Oct 28 '22 15:10

Drew Dormann