Main Content

AUTOSAR C++14 Rule A7-5-1

A function shall not return a reference or a pointer to a parameter that is passed by reference to const

Description

Rule Definition

A function shall not return a reference or a pointer to a parameter that is passed by reference to const.

Rationale

If a parameter is passed to a function by reference to const, a temporary object can be introduced in the function to stand in for this parameter. If you return a reference or a pointer to the parameter, you might be returning a reference or pointer to the temporary object. Since the lifetime of this temporary object ends with the function, accessing a pointer or reference to this object leads to undefined behavior.

Polyspace Implementation

The rule checker reports a violation if you return a pointer or reference to a function parameter that was passed by reference to const.

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

const int & divide_by_factor (int &val, const int &factor) {
    val = val / factor;
    return factor; // Noncompliant
}

void multiply_by_factor (int &val, const int &factor) {
    val = val * factor; // Compliant
}

In this example, the rule checker reports a violation on the return statement in the function divide_by_factor because the function returns a reference to a parameter passed by reference to const. The multiply_by_factor function has the same parameter but does not return a reference to its parameters and therefore does not violate the rule.

Check Information

Group: Declaration
Category: Required, Automated

Version History

Introduced in R2019a