From 5818520b4b19ffa6020ad4d4f5da18078a82bb59 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Fri, 3 Feb 2023 14:10:27 +0100 Subject: [PATCH] Fix FN stlcstrAssignment (#4764) --- lib/checkstl.cpp | 5 +++-- test/teststl.cpp | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index c6919fcce..045a9ad42 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -1976,8 +1976,9 @@ void CheckStl::string_c_str() const Variable* var = tok->variable(); if (var->isPointer()) string_c_strError(tok); - } else if (printPerformance && Token::Match(tok->tokAt(2), "%var% . c_str|data ( ) ;")) { - if (tok->variable() && tok->variable()->isStlStringType() && tok->tokAt(2)->variable() && tok->tokAt(2)->variable()->isStlStringType()) + } else if (printPerformance && tok->tokAt(1)->astOperand2() && Token::Match(tok->tokAt(1)->astOperand2()->tokAt(-3), "%var% . c_str|data ( ) ;")) { + const Token* vartok = tok->tokAt(1)->astOperand2()->tokAt(-3); + if (tok->variable() && tok->variable()->isStlStringType() && vartok->variable() && vartok->variable()->isStlStringType()) string_c_strAssignment(tok); } } else if (printPerformance && tok->function() && Token::Match(tok, "%name% ( !!)") && tok->str() != scope.className) { diff --git a/test/teststl.cpp b/test/teststl.cpp index 7ab9b111d..a488e2c2d 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -4142,6 +4142,19 @@ private: "[test.cpp:12]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n" "[test.cpp:14]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n", errout.str()); + + check("struct S { std::string str; };\n" + "struct T { S s; };\n" + "struct U { T t[1]; };\n" + "void f(const T& t, const U& u, std::string& str) {\n" + " if (str.empty())\n" + " str = t.s.str.c_str();\n" + " else\n" + " str = u.t[0].s.str.c_str();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:6]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n" + "[test.cpp:8]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n", + errout.str()); } void uselessCalls() {