Rule A8-4-7 (required, design, automated)

”in” parameters for ”cheap to copy” types shall be passed by value.

Rationale

Passing an argument by value documents that the argument won’t be modified. Copying the value (instead of passing by reference to const) also ensures that no indirection is needed in the function body to access the value. For the purpose of this rule, ”cheap to copy” is defined as a trivially copyable type that is no longer than two words (i.e. pointers).

Example

// $Id: A8-4-7.cpp 305588 2018-01-29 11:07:35Z michal.szczepankiewicz $

#include <cstdint>
#include <iostream>
#include <string>

// Compliant, pass by value
void output(std::uint32_t i)
{
std::cout << i << ’\n’;
}

// Non-Compliant, std::string is not trivially copyable
void output(std::string s)
{
std::cout << s << ’\n’;
}

struct A
{
std::uint32_t v1;
std::uint32_t v2;
};

// Non-Compliant, A is trivially copyable and no longer than two words
void output(const A &a)
{
std::cout << a.v1 << ", " << a.v2 << ’\n’;
}

See also

C++ Core Guidelines [11]: F.16: For ”in” parameters, pass cheaply-copied types by value and others by reference to const JSF December 2005 [8]: AV Rule 116: Small, concrete-type arguments (two or three words in size) should be passed by value if changes made to formal parameters should not be reflected in the calling function.

JSF December 2005 [8]: AV Rule 117.1: An object should be passed as const T& if the function should not change the value of the object. A18-9-2 in section 6.18.9