Passing an argument by value copies the value to the function parameter. Doing so with fundamental data types is not an issue as copy is not expensive. However, with class types such as strings the copy becomes expensive. So, passing by value for such types is inefficient if the parameter value will be destroyed after brief use.
To solve this issue, we can use pass arguments by references as shown below:
#include <string>
#include <iostream>
void printString(std::string &value)
{
std::cout << value << "\n";
}
int main(int argc, char const *argv[])
{
std::string value{"Hello world"};
printString(value);
return 0;
}Note
It allows the function to change the value of passed argument, which we may be or may not be wanted.
We can only pass modifiable lvalues arguments
We can’t pass a non-modifiable lvalues by reference to a function as lvalue reference can be bind to a modifiable lvalue. So following will be wrong and will give compilation error:
printString("Hello world");
const std::string value{"Bye world"};
printString(value);But this can be solved using pass by const lvalue reference.