From 212d2141d33430bd44f113b5830a7f271f9892a2 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Sun, 12 Nov 2023 10:19:45 +0100 Subject: [PATCH] Fix #12173 FP danglingTempReference with loop over init list (#5652) --- lib/checkautovariables.cpp | 2 ++ test/testautovariables.cpp | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index 61d070fc4..895ee5387 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -471,6 +471,8 @@ static bool isDeadTemporary(bool cpp, const Token* tok, const Token* expr, const if (!precedes(nextAfterAstRightmostLeaf(tok->astTop()), nextAfterAstRightmostLeaf(expr->astTop()))) return false; const Token* parent = tok->astParent(); + if (Token::simpleMatch(parent, "{") && Token::simpleMatch(parent->astParent(), ":")) + parent = parent->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(); diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index 8873ccaef..ede111f1c 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -2144,6 +2144,15 @@ private: " (void)s.i;\n" "}\n"); ASSERT_EQUALS("[test.cpp:8] -> [test.cpp:9]: (error) Using reference to dangling temporary.\n", errout.str()); + + check("std::string f() {\n" // #12173 + " std::string s;\n" + " for (auto& c : { \"a\", \"b\", \"c\" }) {\n" + " s += c;\n" + " }\n" + " return s;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void testglobalnamespace() {