Main Content

CERT C++: EXP61-CPP

A lambda object must not outlive any of its reference captured objects

Description

Rule Definition

A lambda object must not outlive any of its reference captured objects.1

Polyspace Implementation

The rule checker checks for Object Escapes Scope Through Lambda Expression.

Examples

expand all

Issue

The issue occurs when a lambda expression captures an object by reference and the lambda expression object outlives the captured object. For instance, the captured object is a local variable but the lambda expression object has a much larger scope.

Risk

If a lambda expression object outlives one of its reference captured objects, the captured object can be accessed outside its scope.

For instance, consider this function createFunction:

std::function<std::int32_t()> createFunction() {
   std::int32_t localVar = 0;
   return ([&localVar]() -> std::int32_t {
       localVar = 1;
       return localVar;
   });
}

createFunction returns a lambda expression object that captures the local variable localVar by reference. The scope of localVar is limited to createFunction but the lambda expression object returned has a much larger scope.

This situation can result in an attempt to access the local object localVar outside its scope. For instance, when you call createFunction and assign the returned lambda expression object to another object aFunction:

auto aFunction = createFunction();
and then invoke the new object aFunction:
std::int32_t someValue = aFunction();
the captured variable localVar is no longer in scope. Therefore, the value returned from aFunction is undefined.

Fix

If a function returns a lambda expression, to avoid accessing a captured object outside its scope, make sure that the lambda expression captures all objects by copy. For instance, you can rewrite createFunction as:

std::function<std::int32_t()> createFunction() {
   std::int32_t localVar = 0;
   return ([localVar]() mutable -> std::int32_t {
       localVar = 1;
       return localVar;
   });
}

Example – Pointer to Local Variable Escapes Through Lambda Expression
auto createAdder(int amountToAdd) {
  int addThis = amountToAdd; //Noncompliant
  auto adder = [&] (int initialAmount) {
      return (initialAmount + addThis);
  };
  return adder;
}
 
void func() {
  auto AddByTwo = createAdder(2);
  int res = AddByTwo(10);
}

In this example, the createAdder function defines a lambda expression adder that captures the local variable addThis by reference. The scope of addThis is limited to the createAdder function. When the object returned by createAdder is called, a reference to the variable addThis is accessed outside its scope. When accessed in this way, the value of addThis is undefined.

Correction – Capture Local Variables by Copy in Lambda Expression Instead of Reference

If a function returns a lambda expression object, avoid capturing local variables by reference in the lambda object. Capture the variables by copy instead.

auto createAdder(int amountToAdd) {
  int addThis = amountToAdd;
  auto adder = [=] (int initialAmount) {
      return (initialAmount + addThis);
  };
  return adder;
}
 
void func() {
  auto AddByTwo = createAdder(2);
  int res = AddByTwo(10);
}

Check Information

Group: 02. Expressions (EXP)

Version History

Introduced in R2019b


1 This software has been created by MathWorks incorporating portions of: the “SEI CERT-C Website,” © 2017 Carnegie Mellon University, the SEI CERT-C++ Web site © 2017 Carnegie Mellon University, ”SEI CERT C Coding Standard – Rules for Developing safe, Reliable and Secure systems – 2016 Edition,” © 2016 Carnegie Mellon University, and “SEI CERT C++ Coding Standard – Rules for Developing safe, Reliable and Secure systems in C++ – 2016 Edition” © 2016 Carnegie Mellon University, with special permission from its Software Engineering Institute.

ANY MATERIAL OF CARNEGIE MELLON UNIVERSITY AND/OR ITS SOFTWARE ENGINEERING INSTITUTE CONTAINED HEREIN IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. CARNEGIE MELLON UNIVERSITY DOES NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.

This software and associated documentation has not been reviewed nor is it endorsed by Carnegie Mellon University or its Software Engineering Institute.