Main Content

MISRA C++:2023 Rule 9.5.2

A for-range-initializer shall contain at most one function call

Since R2024b

Description

Rule Definition

A for-range-initializer shall contain at most one function call.

Rationale

If a chain of function calls is used in a range-based for-loop initializer, for example,

for (auto it: myData().getValues()) {}
each function returns a temporary object. While the lifetime of the outermost temporary object is extended, the intermediate inner temporaries' lifetimes are not extended and the temporaries are destroyed at the end of the statement. Undefined behavior can result if you attempt to iterate over a temporary object after it has been destroyed.

By limiting the range-based for-loop initialization statement to a single function call, you can avoid iterating over multiple temporary objects and encountering potential issues with their lifetimes. This rule considers use of an overloaded operator and any expression that creates an object of class type to be function calls.

Polyspace Implementation

Polyspace® reports a rule violation whenever more than one function call, object creation, or data member access is attempted during a range-based for-loop initialization statement.

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 <vector>

class Data {
public:
	Data() = default;
	const std::vector<int>& getValues() const;
};

Data myData() {
	return Data{};
}

void example1() {
	for (auto val1 : myData().getValues()) {		// Noncompliant
	}
}

void example2() {
	auto dataVals = myData();

	for (auto val2 : dataVals.getValues()) {		// Compliant
	}
}

The for-loop in example1 violates this rule because it involves calls two functions: getValues() and myData().

The for-loop in example2 complies with the rule by storing the return value of the myData() function in the dataVals object and using that object to invoke the second function, getValues().

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b