Modify rule S6004: CPP-5608 don't raise for for-range

This commit is contained in:
Fred Tingaud 2024-08-21 19:17:55 +02:00 committed by GitHub
parent ed08720fc3
commit 62a8196ac9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 2 additions and 37 deletions

View File

@ -1,5 +1,5 @@
{
"title": "\"if\",\"switch\", and range-based for loop initializer should be used to reduce scope of variables",
"title": "\"if\" and \"switch\" initializer should be used to reduce scope of variables",
"type": "CODE_SMELL",
"code": {
"impacts": {

View File

@ -36,7 +36,7 @@ bool better_init() {
This rule raises an issue when:
- a variable is declared just before a statement that allows variable declaration (`if`, `switch`, or, starting {cpp}20, range-based `for` loop),
- a variable is declared just before a statement that allows variable declaration (`if`, `switch`),
- this variable is used in the statement header,
- there are other statements after this statement where this variable might be used,
- yet, it is never used after the statement.
@ -82,32 +82,6 @@ void switchStatement() {
}
----
[source,cpp]
----
std::vector<std::vector<int>> getTable();
void printHeadersBad() {
auto rows = getTable(); // Noncompliant in C++20: rows is accessible outside of the loop
for (int x : rows[0]) {
std::cout << x <<' ';
}
std::cout << "\n";
}
----
Using a temporary to avoid leaking of the variable into the ambient scope creates a bigger problem: an undefined behavior. Even though the lifetime of a temporary returned by the range expression is extended, the life of a temporary within the range expression terminates before the loop begins to execute.
[source,cpp]
----
std::vector<std::vector<int>> getTable();
void printHeadersWorse() {
for (int x : getTable()[0]) { // Undefined behavior: return value of getTable() no longer exists in the loop body
std::cout << x <<' ';
}
std::cout << "\n";
}
----
=== Compliant solution
[source,cpp]
@ -141,15 +115,6 @@ void switchStatement() {
}
std::cout << "\n";
}
std::vector<std::vector<int>> getTable();
void printHeadersGood() {
// Compliant: rows is accessible only inside the loop (this code requires at least C++20)
for (auto rows = getTable(); int x : table[0]) {
std::cout << x <<' ';
}
std::cout << "\n";
}
----
=== Exceptions