Skip to content

Commit beee36a

Browse files
Fix #14013 FP invalidContainerReference with emplace_back() (danmar#7672)
1 parent 515c73e commit beee36a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/checkstl.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,11 @@ void CheckStl::invalidContainer()
12021202
if (info.tok->variable()->isReference() && !isVariableDecl(info.tok) &&
12031203
reaches(info.tok->variable()->nameToken(), tok, nullptr)) {
12041204

1205+
if ((assignExpr && Token::Match(assignExpr->astOperand1(), "& %varid%", info.tok->varId())) || // TODO: fix AST
1206+
Token::Match(assignExpr, "& %varid% {|(", info.tok->varId())) {
1207+
return false;
1208+
}
1209+
12051210
ErrorPath ep;
12061211
bool addressOf = false;
12071212
const Variable* var = ValueFlow::getLifetimeVariable(info.tok, ep, *mSettings, &addressOf);

test/teststl.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6533,6 +6533,28 @@ class TestStl : public TestFixture {
65336533
ASSERT_EQUALS(
65346534
"[test.cpp:4:7] -> [test.cpp:7:5] -> [test.cpp:8:7]: (error) Calling 'add' while iterating the container is invalid. [invalidContainerLoop]\n",
65356535
errout_str());
6536+
6537+
check("struct S { int i; };\n" // #14013
6538+
"void f() {\n"
6539+
" std::vector<std::unique_ptr<S>> v;\n"
6540+
" for (int i = 0; i < 5; ++i) {\n"
6541+
" std::unique_ptr<S>& r = v.emplace_back(std::make_unique<S>());\n"
6542+
" r->i = 1;\n"
6543+
" }\n"
6544+
"}\n",
6545+
dinit(CheckOptions, $.inconclusive = true));
6546+
ASSERT_EQUALS("", errout_str());
6547+
6548+
check("struct S { int i; };\n"
6549+
"void f() {\n"
6550+
" std::vector<std::unique_ptr<S>> v;\n"
6551+
" for (int i = 0; i < 5; ++i) {\n"
6552+
" std::unique_ptr<S>& r{ v.emplace_back(std::make_unique<S>()) };\n"
6553+
" r->i = 1;\n"
6554+
" }\n"
6555+
"}\n",
6556+
dinit(CheckOptions, $.inconclusive = true));
6557+
ASSERT_EQUALS("", errout_str());
65366558
}
65376559

65386560
void findInsert() {

0 commit comments

Comments
 (0)