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
}
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.
In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.
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.
"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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With