Main Content

AUTOSAR C++14 Rule A8-4-10

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

Since R2021a

Description

Rule Definition

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

Rationale

A reference cannot be NULL. If a parameter is required (it cannot be NULL), pass that parameter by reference to make your intent clearer. Passing by reference also yields cleaner code because you do not need to check whether the parameter is NULL before you use it.

Polyspace Implementation

Polyspace® flags passed-by-pointer parameters except if:

  • The pointer is a smart pointer such as std::shared_ptr.

  • The pointer is not dereferenced in the function.

  • The pointer is checked against NULL, even if the check happens after the dereference.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <iostream>
#include <vector>

void other_func(std::vector<int32_t>*);

void func(std::vector<int32_t>* v_ptr1, //  Non-Compliant
             std::vector<int32_t>* v_ptr2, //  Compliant
             std::vector<int32_t>* v_ptr3) //  Compliant
{

    auto v = v_ptr1;
    auto ptr_size = 0;
    if (v_ptr2 != NULL) {
        ptr_size = v_ptr2->size();
    }
    v->resize(ptr_size);

    other_func(v_ptr3);
    //....

}

In this example pass-by-pointer parameter v_ptr1 is non-compliant because it is dereferenced inside func without checking if the pointer is NULL. If v_ptr1 cannot be NULL, pass this parameter by reference. If the v_ptr1 can be NULL, check whether the pointer is NULL before you dereference it to avoid a segmentation fault.

Parameter v_ptr2 is compliant because it is checked against NULL, which indicates it could be NULL.

v_ptr3 is compliant because it is not dereferenced inside func.

Check Information

Group: Declarators
Category: Required, Automated

Version History

Introduced in R2021a

Go to top of page