diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 250d49f51..f5ef77ef3 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -1769,6 +1769,22 @@ void CheckOther::functionVariableUsage() tok = tok->next(); } + // std::string declaration with possible initialization + // std::string s; std::string s = "string"; + else if (Token::Match(tok, "[;{}] static| std :: string %var% ;|=")) + { + tok = tok->next(); + + const bool isStatic = tok->str() == "static"; + if (isStatic) + tok = tok->next(); + + tok = tok->tokAt(3); + variables.addVar(tok, Variables::standard, info, + tok->next()->str() == "=" || isStatic); + tok = tok->next(); + } + // standard struct type declaration with possible initialization // struct S s; struct S s = { 0 }; static struct S s; else if (Token::Match(tok, "[;{}] static| struct %type% %var% ;|=") && diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index b734cb0d8..0134e8bd0 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -98,6 +98,7 @@ private: TEST_CASE(localvarstatic); TEST_CASE(localvardynamic); TEST_CASE(localvararray1); // ticket #2780 + TEST_CASE(localvarstring); // Don't give false positives for variables in structs/unions TEST_CASE(localvarStruct1); @@ -2781,6 +2782,37 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); } + + void localvarstring() // ticket #1597 + { + functionVariableUsage("void foo() {\n" + " std::string s;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Unused variable: s\n", errout.str()); + + functionVariableUsage("void foo() {\n" + " std::string s;\n" + " s = \"foo\";\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used\n", errout.str()); + + functionVariableUsage("void foo() {\n" + " std::string s = \"foo\";\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used\n", errout.str()); + + functionVariableUsage("std::string foo() {\n" + " std::string s;\n" + " return s;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is not assigned a value\n", errout.str()); + + functionVariableUsage("std::string foo() {\n" + " std::string s = \"foo\";\n" + " return s;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } }; REGISTER_TEST(TestUnusedVar)