Qt-Autosar-A5.1.9

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

Required inputs: IR

Rationale

Code duplication reduces readability and maintainability as it might not be obvious that the lambda expressions are identical and any changes need to be applied in more than one place.

Example
// $Id: A5-1-9.cpp 307019 2018-02-09 15:16:47Z christof.meerwald $
    #include <algorithm>
    #include <cstdint>
    #include <vector>

    void Fn1(const std::vector<int16_t> &v)
    {
        // Non-compliant: identical unnamed lambda expression
        if (std::none_of(v.begin(), v.end(),
                [] (int16_t i) { return i < 0; }))
        {
            // ...
        }
        else if (std::all_of(v.begin(), v.end(),
                [] (int16_t i) { return i < 0; }))
        {
            // ...
        }
    }

    void Fn2(const std::vector<int16_t> &v)
    {
          // Compliant: re-using lambda expression
          auto is_negative = [] (int16_t i) { return i < 0; };

          if (std::none_of(v.begin(), v.end(), is_negative))
          {
              // ...
          }
          else if (std::all_of(v.begin(), v.end(), is_negative))
          {
              // ...
          }
    }
See Also
  • C++ Core Guidelines [11]: T.141: Use an unnamed lambda if you need a simple function object in one place only.

Possible Messages

Key

Text

Severity

Disabled

identical_unnamed_lambda

Identical unnamed lambdas.

None

False

Options

allow_empty_lambdas

allow_empty_lambdas : bool = False

If set to true, this rule will not report duplicates of the trivial empty lambda.