Main Content

MISRA C++:2008 Rule 7-5-3

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

Description

Rule Definition

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

Rationale

If a parameter is passed to a function by reference, depending on the implementation, 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 is passed by reference.

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

int * multiply_by_factor (int &val, int factor) {
    val = val * factor;
    return &val; //Noncompliant
}

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

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

In this example:

  • The function multiply_by_factor returns a pointer to a value passed by reference.

  • The function divide_by_factor returns a reference to a parameter passed by const reference.

Polyspace reports violations on these return statements of these functions. Because the function multiply_by_factor_compliant does not return anything, this function is compliant with this rule.

Check Information

Group: Declarations
Category: Required

Version History

Introduced in R2013b