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
8 changes: 5 additions & 3 deletions lib/checkother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2920,9 +2920,11 @@ void CheckOther::checkRedundantCopy()
const Token* startTok = var->nameToken();
if (startTok->strAt(1) == "=") // %type% %name% = ... ;
;
else if (Token::Match(startTok->next(), "(|{") && var->isClass() && var->typeScope()) {
else if (Token::Match(startTok->next(), "(|{") && var->isClass()) {
if (!var->typeScope() && !(var->valueType() && var->valueType()->container))
continue;
// Object is instantiated. Warn if constructor takes arguments by value.
if (constructorTakesReference(var->typeScope()))
if (var->typeScope() && constructorTakesReference(var->typeScope()))
continue;
} else if (Token::simpleMatch(startTok->next(), ";") && startTok->next()->isSplittedVarDeclEq()) {
startTok = startTok->tokAt(2);
Expand All @@ -2934,7 +2936,7 @@ void CheckOther::checkRedundantCopy()
continue;
if (!Token::Match(tok->previous(), "%name% ("))
continue;
if (!Token::Match(tok->link(), ") )| ;")) // bailout for usage like "const A a = getA()+3"
if (!Token::Match(tok->link(), ") )|}| ;")) // bailout for usage like "const A a = getA()+3"
continue;

const Token* dot = tok->astOperand1();
Expand Down
16 changes: 16 additions & 0 deletions test/testother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9047,6 +9047,22 @@ class TestOther : public TestFixture {
"[test.cpp:16] -> [test.cpp:18]: (style) The comparison 'c == m->get()' is always true because 'c' and 'm->get()' represent the same value.\n",
errout_str());

check("struct S {\n" // #12925
" const std::string & f() const { return str; }\n"
" std::string str;\n"
"};\n"
"void f(const S* s) {\n"
" const std::string v{ s->f() };\n"
" if (v.empty()) {}\n"
"}\n"
"void g(const S* s) {\n"
" const std::string w(s->f());\n"
" if (w.empty()) {}\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (performance, inconclusive) Use const reference for 'v' to avoid unnecessary data copying.\n"
"[test.cpp:10]: (performance, inconclusive) Use const reference for 'w' to avoid unnecessary data copying.\n",
errout_str());

check("struct T {\n"
" std::string s;\n"
" const std::string& get() const { return s; }\n"
Expand Down