I was studying about advanced topics, and came across a question in my mind - why would I need to use pass-by-value instead of pass-by-reference?
The question is originated around memory management, which is, if passing a variable as a value into a function makes a copy of the variable, shouldn't I need to pass it by reference as const to efficiently use memory?
When I researched on Google, it generally stated that pass-by-value should be used when we don't want to change the variable inside of a function.
Here is my example below:
#include <iostream>
void foo(int a) {
std::cout << "value of a: " << a << std::endl;
}
int main(){
int b = 5;
foo(5);
return EXIT_SUCCESS;
}
In the code block above, I passed b
as value into the function foo()
. Which made a copy of b
.
Instead, if I write the function like below:
#include <iostream>
void foo(const int& a) {
std::cout << "value of a: " << a << std::endl;
}
int main(){
int b = 5;
foo(5);
return EXIT_SUCCESS;
}
With this code block, I don't make a copy of b
.
What are the advantages of using pass-by-value when I am calling functions instead of pass-by-reference, besides when I don't want to change the content of the variable inside of a function?