From 53734a3da1dd394aee9398127692b0e38e9ffa9f Mon Sep 17 00:00:00 2001 From: shaneasd Date: Mon, 28 Dec 2020 17:50:42 +0800 Subject: [PATCH] Test for return address of reference (#2991) --- lib/valueflow.cpp | 3 ++- test/testautovariables.cpp | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 4ca8d88c1..8ece5b7fa 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -2742,7 +2742,8 @@ std::vector getLifetimeTokens(const Token* tok, bool escape, Valu } else if (Token::simpleMatch(var->declEndToken(), "=")) { errorPath.emplace_back(var->declEndToken(), "Assigned to reference."); const Token *vartok = var->declEndToken()->astOperand2(); - const bool temporary = isTemporary(true, vartok, nullptr, true); + const bool temporaryDefault = false; //If we can't tell then assume the value is not temporary as this will result in fewer false positives. + const bool temporary = isTemporary(true, vartok, nullptr, temporaryDefault); const bool nonlocal = var->isStatic() || var->isGlobal(); if (vartok == tok || (nonlocal && temporary) || (!escape && (var->isConst() || var->isRValueReference()) && temporary)) return {{tok, true, std::move(errorPath)}}; diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index aa79e9258..bfc9439ff 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -2564,6 +2564,21 @@ private: " }\n" "};\n"); ASSERT_EQUALS("", errout.str()); + + //Make sure we can still take the address of a reference without warning + check("int* foo() {\n" + " int& x = getX();\n" + " return &x;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + check("struct C {\n" + " int* m_x;\n" + " void foo() {\n" + " const int& x = getX();\n" + " m_x = &x;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void danglingLifetimeFunction() {