Choosing well among values, references, and pointers for parameters is good habit that maximizes both safety and efficiency.
Although efficiency should not be our primary up-front concern (see Item 8), neither should we write needlessly inefficient code when all other things, including clarity, are equal (see Item 9).
Prefer to follow these guidelines for choosing how to take parameters. For input-only parameters:
- Always const -qualify all pointers or references to input-only parameters.
- Prefer taking inputs of primitive types (e.g., char, float ) and value objects that are cheap to copy (e.g., Point, complex<float> ) by value.
- Prefer taking inputs of other user-defined types by reference to const .
- Consider pass-by-value instead of reference if the function requires a copy of its argument. This is conceptually identical to taking a reference to const plus doing a copy, and it can help compiler to better optimize away temporaries.
For output or input/output parameters:
- Prefer passing by (smart) pointer if the argument is optional (so callers can pass null as a "not available" or "don't care" value) or if the function stores a copy of the pointer or otherwise manipulates ownership of the argument.
- Prefer passing by reference if the argument is required and the function won't store a pointer to it or otherwise affect its ownership. This states that the argument is required and makes the caller responsible for providing a valid object.
Don't use C-style varargs (see Item 98).