AutosarC++17_10-A5.1.5

If a lambda expression is used in the same scope in which it has been defined, the lambda should capture objects by reference

Required inputs: IR

Rationale

Copying objects captured to lambda by value may be a performance overhead. It is correct to capture objects by reference when using the lambda expression locally only.

Exceptions

It is permitted to capture by copy objects that size is lesser or equal to 16 bytes (i.e.

4 * sizeof(std::uint32_t)).

Example
// $Id: A5-1-5.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
#include <functional>
namespace {
constexpr std::int32_t bufferMax = 1024;
constexpr std::int8_t receiversMax = 10;
} // namespace
class UDPClient {
  // Implementation - size of UDPClient class exceeds 16 bytes
};
void F1() noexcept(false) {
  UDPClient client;
  std::uint8_t buffer[bufferMax];
  auto lambda1 = [client,
                  buffer]() // Non-compliant - it is inefficient to capture
                            // UDPClient and buffer objects by copy in lambda
  {
    // Code
  };
  lambda1(); // lambda1 used locally only

  auto lambda2 =
      [&client, &buffer]() // Compliant - be aware that this construct
  // may introduce data races in parallel calls.
  {
    // Code
  };
  lambda2(); // lambda2 used locally only

  std::uint32_t number1 = 10;
  std::uint32_t number2 = 20;
  auto lambda3 = [number1, number2]() //   Compliant by exception - the size of
                                      //   std::uint32_t is 4 bytes (lesser or
                                      //   equal to the size of a pointer -
                                      //   depending on architecture)
  {
    // Code
  };
  lambda3(); // lambda3 used locally only
}
void F2(std::int8_t currentReceiver) noexcept(false) {
  std::function<void()> receiver;

  if (currentReceiver < receiversMax) {
    UDPClient client;
    receiver = [&client]() // Non-compliant - lambda is not used locally, client
                           // object will go out of scope
    {
      // Code
    };
  }

  // ...
  receiver(); // Undefined behavior, client object went out of scope
}
See Also
  • C++ Core Guidelines [10]: F.52: Prefer capturing by reference in lambdas that will be used locally, including passed to algorithms captured objects.

Possible Messages

Key

Text

Severity

Disabled

local_lambda

An only locally used lambda should capture by reference.

None

False

Options

ignore_as_argument_of_functions

ignore_as_argument_of_functions : set[bauhaus.analysis.config.QualifiedName] = set()

A set of fully qualified function names where the rule can assume that no reference to the passed-in lambda is kept, thus allowing the lambda to not capture by reference.