Fixed #10266 (False positive; parameter can be const)

This commit is contained in:
Daniel Marjamäki 2021-05-08 13:40:52 +02:00
parent abb4200316
commit a197e94573
2 changed files with 34 additions and 6 deletions

View File

@ -1413,13 +1413,35 @@ void CheckOther::checkConstVariable()
//Is it the right side of an initialization of a non-const reference
bool usedInAssignment = false;
for (const Token* tok = var->nameToken(); tok != scope->bodyEnd && tok != nullptr; tok = tok->next()) {
if (!Token::Match(tok, "& %var% = %varid%", var->declarationId()))
continue;
if (Token::Match(tok, "& %var% = %varid%", var->declarationId())) {
const Variable* refvar = tok->next()->variable();
if (refvar && !refvar->isConst() && refvar->nameToken() == tok->next()) {
usedInAssignment = true;
break;
}
} else if (Token::Match(tok, "auto &| [")) {
// structured binding taking reference..
const Token *tok2 = tok->next();
if (tok2->str() == "&")
tok2 = tok2->next();
tok2 = tok2->link();
if (Token::Match(tok2, "] [:=] %varid% [);]", var->declarationId())) {
if (tok->next()->str() == "&") {
usedInAssignment = true;
break;
}
while (tok2 != tok) {
if (tok2->varId()) {
const Variable* refvar = tok2->variable();
if (!refvar || (!refvar->isConst() && refvar->isReference())) {
usedInAssignment = true;
break;
}
}
tok2 = tok2->previous();
}
}
}
}
if (usedInAssignment)
continue;

View File

@ -2596,6 +2596,12 @@ private:
"{\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:16]: (style) Parameter 'i' can be declared with const\n", "", errout.str());
check("void f(std::map<int, std::vector<int>> &map) {\n" // #10266
" for (auto &[slave, panels] : map)\n"
" panels.erase(it);\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void constParameterCallback() {