Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/checkstl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions test/teststl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4142,6 +4142,19 @@ class TestStl : public TestFixture {
"[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() {
Expand Down