Main Content

Useless capture

Lambda captures objects but does not use the objects

Since R2024b

Description

This defect occurs when a lambda expression captures objects either implicitly or explicitly, but does not use them. For example, the lambda L1 captures the objects of its scope implicitly by reference but uses none of them:

auto L1 = [&](){}; 
Polyspace® reports this defect for L1.

Risk

An unused captured object can indicate possible logic errors or architectural errors in your code. Useless captures prevent the lambda from being assigned to a function pointer. If an unused captured object is expensive to construct or destroy, then it can make the code unnecessarily expensive.

Fix

To fix this defect, review your code and determine why captured objects are unused. Remove useless captures from your lambda expressions.

Examples

expand all

In this C++ example, the string error is captured by a lambda but not used. Polyspace reports a defect.

#include <functional>
#include <memory>
#include <string>

extern void set_callback(std::function<void()> cb);

void non_compliant(std::shared_ptr<std::function<void()>> task)
{
	std::string error("Task Error");

	set_callback([error, task]() {
		(*task)();
	});            
}
Correction — Remove Unused Variable

To fix this defect, do not capture the string error in the lambda.

#include <functional>
#include <memory>

extern void set_callback(std::function<void()> cb);

void compliant(std::shared_ptr<std::function<void()>> task)
{
	set_callback([task]() {
		(*task)();
	});                  
}

Result Information

Group: Good Practice
Language: C++
Default: Off
Command-Line Syntax: USELESS_CAPTURE
Impact: Low

Version History

Introduced in R2024b