Main Content

AUTOSAR C++14 Rule A5-1-9

Identical unnamed lambda expressions shall be replaced with a named function or a named lambda expression

Since R2020b

Description

Rule Definition

Identical unnamed lambda expressions shall be replaced with a named function or a named lambda expression.

Rationale

When you reuse an unnamed lambda expression, you insert the body of that lambda expression wherever you invoke it in your code. This code duplication might result in maintainability issues when you make changes, as you might misidentify which lambda expressions are identical when applying those changes. The code duplication also decreases the readability of your code.

Polyspace Implementation

After the first use of an unnamed lambda expression, Polyspace® flags each subsequent uses of an identical lambda expression. For instance, if you reuse the same lambda expression three times, Polyspace flags the second and third uses of the lambda expression as separate violations. Polyspace also highlights the first use of the unnamed lambda expression in your source code.

Polyspace does not flag the reuse of global scope lambda expressions.

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<vector>
#include<algorithm>


void func1(std::vector<int>& v)
{
    if (none_of(v.begin(), v.end(),
    [](int i) {return i % 2 == 1;})) {
        //Handle error
    }

    int odds = std::count_if(v.begin(), v.end(),
    [](int i) {return i % 2 == 1;}); //Noncompliant

    std::vector<int>::iterator first_odd = find_if(v.begin(), v.end(),
    [](int i) {return i % 2 == 1;}); //Noncompliant
}

void func2(std::vector<int>& v)
{
    auto is_odd = [](int i) { return i % 2 == 1;};

    if (none_of(v.begin(), v.end(), is_odd)) {
        //Handle error
    }

    int odds = std::count_if(v.begin(), v.end(), is_odd); //Compliant,
                                                          //reusing named lambda expression 

    std::vector<int>::iterator first_odd = find_if(v.begin(),
            v.end(), is_odd); //Compliant, reusing named lambda expression
}

In this example, unnamed lambda expression [](int i) {return i % 2 == 1;} is reused twice inside func1. Polyspace flags the second and third uses of this lambda expression.

The reuse of the lambda expression in func2 is not flagged because the lambda expression is named (is_odd).

Check Information

Group: Expressions
Category: Advisory, Automated

Version History

Introduced in R2020b