Fixed #4956 (false positive: Variable 'myIsFirst' is assigned a value that is never used.)

This commit is contained in:
Daniel Marjamäki 2013-10-26 15:22:28 +02:00
parent aaf5bbb7ad
commit 853d9dd7a9
2 changed files with 31 additions and 0 deletions

View File

@ -780,6 +780,24 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
}
}
// C++11 std::for_each
// No warning should be written if a variable is first read and
// then written in the body.
if (Token::simpleMatch(tok, "for_each (") && Token::simpleMatch(tok->linkAt(1), ") ;")) {
const Token *end = tok->linkAt(1);
if (end->previous()->str() == "}") {
std::set<unsigned int> readvar;
for (const Token *body = end->linkAt(-1); body != end; body = body->next()) {
if (body->varId() == 0U)
continue;
if (!Token::Match(body->next(),"="))
readvar.insert(body->varId());
else if (readvar.find(body->varId()) != readvar.end())
variables.erase(body->varId());
}
}
}
if (Token::Match(tok->previous(), "[;{}]")) {
for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId()) {

View File

@ -3084,6 +3084,19 @@ private:
" }\n"
"}");
ASSERT_EQUALS("[test.cpp:6]: (style) Variable 'i' is assigned a value that is never used.\n", errout.str());
// #4956 - assignment in for_each
functionVariableUsage("void f(std::vector<int> ints) {\n"
" int x = 0;\n"
" std::for_each(ints.begin(), ints.end(), [&x](int i){ dostuff(x); x = i; });\n"
"}");
ASSERT_EQUALS("", errout.str());
functionVariableUsage("void f(std::vector<int> ints) {\n"
" int x = 0;\n"
" std::for_each(ints.begin(), ints.end(), [&x](int i){ x += i; });\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'x' is assigned a value that is never used.\n", errout.str());
}
void localvarShift1() {