Understand function parameter semantics
Pass by reference or pass by value?
Section titled “Pass by reference or pass by value?”Refer to the Core Guidelines:
- F.15: Prefer simple and conventional ways of passing information
- F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to
const
”in” parameters
Section titled “”in” parameters”For small objects:
- passing by value is idiomatic, clear, and can often by optimized by compilers.
For large objects:
- passing const& avoids expensive copying, but can inhibit optimizations, because the compiler must assume the reference could alias other memory.
An object is considered small if its size is similar to or less than the size of a few primitive types, like 1-2 pointers, 2-3 doubles, or less than 32 bytes).
Core guidelines suggests less or equal than 2 * sizeof(void*)
Herb Sutter mentions in CppCon 2014 special case for constructors:
- For constructors, pass by value and move can be good. No chance to reuse buffers/state anyway.