From 02ae71917a8b8f7890ef5e950243b987a8a43892 Mon Sep 17 00:00:00 2001 From: Paul Fultz II Date: Wed, 1 Apr 2020 15:35:41 -0500 Subject: [PATCH] Fix issue 9536: False positive: Reference to temporary returned when using operator() (#2582) * Fix issue 9536: False positive: Reference to temporary returned when using operator() * Add more test cases --- lib/astutils.cpp | 5 +++++ test/testautovariables.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/astutils.cpp b/lib/astutils.cpp index 80a752fb2..befd66053 100644 --- a/lib/astutils.cpp +++ b/lib/astutils.cpp @@ -254,6 +254,11 @@ bool isTemporary(bool cpp, const Token* tok, const Library* library, bool unknow return unknown; } } + if (tok->isCast()) + return false; + // Currying a function is unknown in cppcheck + if (Token::simpleMatch(tok, "(") && Token::simpleMatch(tok->astOperand1(), "(")) + return unknown; return true; } diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index 49bd45770..2b4560de7 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -114,6 +114,7 @@ private: TEST_CASE(returnReference17); // #9461 TEST_CASE(returnReference18); // #9482 TEST_CASE(returnReference19); // #9597 + TEST_CASE(returnReference20); // #9536 TEST_CASE(returnReferenceFunction); TEST_CASE(returnReferenceContainer); TEST_CASE(returnReferenceLiteral); @@ -1316,6 +1317,34 @@ private: ASSERT_EQUALS("", errout.str()); } + // #9536 + void returnReference20() { + check("struct a {\n" + " int& operator()() const;\n" + "};\n" + "int& b() {\n" + " return a()();\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + check("auto a() {\n" + " return []() -> int& {\n" + " static int b;\n" + " return b;\n" + " };\n" + "}\n" + "const int& c() {\n" + " return a()();\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + check("std::function a();\n" + "int& b() {\n" + " return a()();\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } + void returnReferenceFunction() { check("int& f(int& a) {\n" " return a;\n"