Main Content

AUTOSAR C++14 Rule A5-1-8

Lambda expressions should not be defined inside another lambda expression

Since R2020b

Description

Rule Definition

Lambda expressions should not be defined inside another lambda expression.

Rationale

Developers can use lambda expressions to write anonymous function objects that contain a few lines of code. Nesting lambda expression reduces the readability of the code because the body of a lambda expression is typically in the line where it is used. For instance, the find_if algorithm takes a unary predicate as one of its arguments. A developer can use a lambda expression to define a predicate condition in the declaration of find_if. In this code snippet, the find_if algorithm returns the first member of a vector of integers that is greater than 2 and that is even.

std::vector<int> v = { 1, 2, 3, 4 };
std::find(v.begin(), v.end(),
    [](int val) { return val>2 && val%2==0;});

Polyspace Implementation

Polyspace® flags lambda expressions that are defined inside another lambda expression. Polyspace also highlights the closest nesting lambda expression.

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

int main()
{

    using namespace std;

    vector<int> v {1, 2, 3, 4};


    vector<int>::iterator it = v.begin();
    while (it != v.end()) {
        auto evenGreater2 = [](int val) {

            return [](int val2) { //Noncompliant
                return val2 % 2 == 0;
            }(val)&& (val) > 2;

        }(*it);


        if (evenGreater2) {
            cout << *it << endl;
            break;
        }
        ++it;
    }

}

In this example, Polyspace flags the lambda expression that checks whether a value is even ([](int val2) { return val2 % 2 ==0; }) because it is nested inside another lambda expression that also checks whether a value is greater than 2.

Check Information

Group: Expressions
Category: Advisory, Automated

Version History

Introduced in R2020b