- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 216字
- 2021-06-10 18:28:04
Using function parameters
When a function is called, the compiler checks all the overloads of the function to find one that matches the parameters in the calling code. If there is no exact match then standard and user-defined type conversions are performed, so the values provided by the calling code may be a different type from the parameters.
By default, parameters are passed by value and a copy is made, which means that the parameters are treated as local variables in the function. The writer of the function can decide to pass a parameter by reference, either through a pointer or a C++ reference. Pass-by-reference means that the variable in the calling code can be altered by the function, but this can be controlled by making the parameters const, in which case the reason for pass-by-reference is to prevent a (potentially costly) copy being made. Built-in arrays are always passed as a pointer to the first item to the array. The compiler will create temporaries when needed. For example, when a parameter is a const reference and the calling code passes a literal, a temporary object is created, and is only available to code in the function:
void f(const float&);
f(1.0); // OK, temporary float created
double d = 2.0;
f(d); // OK, temporary float created