Skip to content

Commit 5818520

Browse files
Fix FN stlcstrAssignment (#4764)
1 parent e8c3a80 commit 5818520

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

lib/checkstl.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1976,8 +1976,9 @@ void CheckStl::string_c_str()
19761976
const Variable* var = tok->variable();
19771977
if (var->isPointer())
19781978
string_c_strError(tok);
1979-
} else if (printPerformance && Token::Match(tok->tokAt(2), "%var% . c_str|data ( ) ;")) {
1980-
if (tok->variable() && tok->variable()->isStlStringType() && tok->tokAt(2)->variable() && tok->tokAt(2)->variable()->isStlStringType())
1979+
} else if (printPerformance && tok->tokAt(1)->astOperand2() && Token::Match(tok->tokAt(1)->astOperand2()->tokAt(-3), "%var% . c_str|data ( ) ;")) {
1980+
const Token* vartok = tok->tokAt(1)->astOperand2()->tokAt(-3);
1981+
if (tok->variable() && tok->variable()->isStlStringType() && vartok->variable() && vartok->variable()->isStlStringType())
19811982
string_c_strAssignment(tok);
19821983
}
19831984
} else if (printPerformance && tok->function() && Token::Match(tok, "%name% ( !!)") && tok->str() != scope.className) {

test/teststl.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4142,6 +4142,19 @@ class TestStl : public TestFixture {
41424142
"[test.cpp:12]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n"
41434143
"[test.cpp:14]: (performance) Passing the result of c_str() to a stream is slow and redundant.\n",
41444144
errout.str());
4145+
4146+
check("struct S { std::string str; };\n"
4147+
"struct T { S s; };\n"
4148+
"struct U { T t[1]; };\n"
4149+
"void f(const T& t, const U& u, std::string& str) {\n"
4150+
" if (str.empty())\n"
4151+
" str = t.s.str.c_str();\n"
4152+
" else\n"
4153+
" str = u.t[0].s.str.c_str();\n"
4154+
"}\n");
4155+
ASSERT_EQUALS("[test.cpp:6]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n"
4156+
"[test.cpp:8]: (performance) Assigning the result of c_str() to a std::string is slow and redundant.\n",
4157+
errout.str());
41454158
}
41464159

41474160
void uselessCalls() {

0 commit comments

Comments
 (0)