Rule M8-4-4 (required, implementation, automated)

A function identifier shall either be used to call the function or it shall be preceded by &. See MISRA C++ 2008 [7] Rule A8-4-3 (advisory, design, non-automated) Common ways of passing parameters should be used.

Rationale

Using common and well-understood parameter passing patterns as summarised in the following table helps meeting developer expectations. in in/out out consume forward

cheap to copy or move only f(X)

cheap to move expensive to move f(const X &) f(X &) X f() f(X &) f(X &&) template f(T &&)

Parameter passing

Example

// $Id: A8-4-3.cpp 308906 2018-02-23 15:34:15Z christof.meerwald $

#include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <string>
#include <vector>

// Compliant: passing cheap-to-copy parameter by value
int32_t Increment(int32_t i)
{
return i + 1;
}

// Compliant: passing expensive to copy parameter by reference to const
int32_t Sum(const std::vector<int32_t> &v)
{
return std::accumulate(v.begin(), v.end(), 0);
}

// Compliant: passing in-out parameter by reference
void Decrement(int32_t &i)
{

--i;

}

// Compliant: returning out parameter by value
std::string GetGreeting()
{
return "Hello";
}

struct A
{
std::string text;
std::array<std::string, 1000> arr;
};

// Expensive to move "out" parameter passed by reference. If
// intentional, violation of A8-4-8 needs to be explained
void InitArray(std::array<std::string, 1000> &arr,
const std::string &text)
{
std::for_each(arr.begin(), arr.end(), [&text] (std::string &s) {
s = text;
});
}

// Compliant: passing in-out parameter by reference
void PopulateA(A &a)
{
InitArray(a.arr, a.text);
}

See also

C++ Core Guidelines [11]: F.16: Prefer simple and conventional ways of passing information