Fix issue 9852: False positive: danglingTemporaryLifetime when returning a vector of vectors (#2766)

This commit is contained in:
Paul Fultz II 2020-09-01 04:21:29 -05:00 committed by GitHub
parent 3e99bff764
commit 0a718694af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 2 deletions

View File

@ -445,8 +445,17 @@ static bool isDeadTemporary(bool cpp, const Token* tok, const Token* expr, const
{
if (!isTemporary(cpp, tok, library))
return false;
if (expr && !precedes(nextAfterAstRightmostLeaf(tok->astTop()), nextAfterAstRightmostLeaf(expr->astTop())))
return false;
if (expr) {
if (!precedes(nextAfterAstRightmostLeaf(tok->astTop()), nextAfterAstRightmostLeaf(expr->astTop())))
return false;
const Token* parent = tok->astParent();
// Is in a for loop
if (astIsRHS(tok) && Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "(") && Token::simpleMatch(parent->astParent()->previous(), "for (")) {
const Token* braces = parent->astParent()->link()->next();
if (precedes(braces, expr) && precedes(expr, braces->link()))
return false;
}
}
return true;
}

View File

@ -2142,6 +2142,13 @@ private:
" return std::vector<char*>{&a};\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3] -> [test.cpp:2] -> [test.cpp:3]: (error) Returning object that points to local variable 'a' that will be invalid when returning.\n", errout.str());
check("std::vector<std::vector<int>> g();\n"
"void f() {\n"
" for(auto& x:g())\n"
" std::sort(x.begin(), x.end());\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
void danglingLifetime() {