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

A parameter shall be passed by reference if it can’t be NULL

Rationale

Passing a parameter by pointer suggests that it can be NULL. If it can’t be NULL (i.e. it’s not optional) it should therefore be passed by reference instead. Only parameters that can be NULL shall be passed by pointer. Note: The C++ Library Fundamentals TS v2 defines std::observer_ptr as a near dropin replacement for raw pointers that makes it explicit that the object is not owned by the pointer. Note: boost::optional supports reference types, and in C++17 std::optional can be used in conjunction with std::reference_wrapper (using std::optional with a value type would create an undesirable copy of the object)

Example

// $Id: A8-4-10.cpp 307966 2018-02-16 16:03:46Z christof.meerwald $

#include <cstdint>
#include <numeric>
#include <vector>

// Non-Compliant: non-optional parameter passed by pointer

int32_t Sum(const std::vector<int32_t> *v)

{
return std::accumulate(v->begin(), v->end(), 0);

}

// Compliant: non-optional parameter passed by reference
int32_t Sum(const std::vector<int32_t> &v)
{
return std::accumulate(v.begin(), v.end(), 0);
}

See also

C++ Core Guidelines [11]: F.60: Prefer T* over T& when "no argument" is a valid option JSF December 2005 [8]: AV Rule 118: Arguments should be passed via pointers if NULL values are possible. JSF December 2005 [8]: AV Rule 118.1: An object should be passed as const T* if its value should not be modified. JSF December 2005 [8]: AV Rule 118.2: An object should be passed as T* if its value may be modified.