Skip to main content

13.11) Using const References To Avoid Copying


Call-by-value semantics means that 'large' arguments (e.g., vectors) will be copied when passed to functions, even if the function won't need to change the argument. Passing by reference will avoid the potentially costly copy operation, but suggests to users of the function that it might change its arguments in some way.

In such cases, it is a good idea to declare the parameter as a const reference, so that it cannot be changed by the function (any attempt to do so inside the function would result in a compiler error):

void process_data(const vector<double>& data)
{
...
}

Note: use this only for potentially large arguments (vectors, strings, etc); it isn't necessary for simple scalar types such as int, double, etc.