diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index cbd90027b..e1b86f394 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -1595,9 +1595,13 @@ void CheckStl::checkFindInsertError(const Token *tok) { std::string replaceExpr; if (tok && Token::simpleMatch(tok->astParent(), "=") && tok == tok->astParent()->astOperand2() && Token::simpleMatch(tok->astParent()->astOperand1(), "[")) { + if (mSettings->standards.cpp < Standards::CPP11) + // We will recommend using emplace/try_emplace instead + return; + const std::string f = (mSettings->standards.cpp < Standards::CPP17) ? "emplace" : "try_emplace"; replaceExpr = " Instead of '" + tok->astParent()->expressionString() + "' consider using '" + tok->astParent()->astOperand1()->astOperand1()->expressionString() + - (mSettings->standards.cpp < Standards::CPP17 ? ".insert(" : ".emplace(") + + "." + f + "(" + tok->astParent()->astOperand1()->astOperand2()->expressionString() + ", " + tok->expressionString() + diff --git a/test/teststl.cpp b/test/teststl.cpp index 444a2abe2..60098eacf 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -5153,16 +5153,40 @@ private: ASSERT_EQUALS("[test.cpp:3]: (performance) Searching before insertion is not necessary.\n", errout.str()); } - check("void foo() {\n" - " std::map x;\n" - " int data = 0;\n" - " for(int i=0; i<10; ++i) {\n" - " data += 123;\n" - " if(x.find(5) == x.end())\n" - " x[5] = data;\n" - " }\n" - "}"); - ASSERT_EQUALS("[test.cpp:7]: (performance) Searching before insertion is not necessary. Instead of 'x[5]=data' consider using 'x.emplace(5, data);'.\n", errout.str()); + { // #10558 + check("void foo() {\n" + " std::map x;\n" + " int data = 0;\n" + " for(int i=0; i<10; ++i) {\n" + " data += 123;\n" + " if(x.find(5) == x.end())\n" + " x[5] = data;\n" + " }\n" + "}", false, Standards::CPP03); + ASSERT_EQUALS("", errout.str()); + + check("void foo() {\n" + " std::map x;\n" + " int data = 0;\n" + " for(int i=0; i<10; ++i) {\n" + " data += 123;\n" + " if(x.find(5) == x.end())\n" + " x[5] = data;\n" + " }\n" + "}", false, Standards::CPP11); + ASSERT_EQUALS("[test.cpp:7]: (performance) Searching before insertion is not necessary. Instead of 'x[5]=data' consider using 'x.emplace(5, data);'.\n", errout.str()); + + check("void foo() {\n" + " std::map x;\n" + " int data = 0;\n" + " for(int i=0; i<10; ++i) {\n" + " data += 123;\n" + " if(x.find(5) == x.end())\n" + " x[5] = data;\n" + " }\n" + "}"); + ASSERT_EQUALS("[test.cpp:7]: (performance) Searching before insertion is not necessary. Instead of 'x[5]=data' consider using 'x.try_emplace(5, data);'.\n", errout.str()); + } } void checkKnownEmptyContainer() {