Skip to content

Commit 9eba96e

Browse files
Fix #12935 FP unassignedVariable with static empty QString in function (#6599)
1 parent ecd73d5 commit 9eba96e

3 files changed

Lines changed: 29 additions & 1 deletion

File tree

lib/checkunusedvar.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1149,6 +1149,16 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const
11491149
}
11501150
}
11511151

1152+
static bool isReturnedByRef(const Variable* var, const Function* func)
1153+
{
1154+
if (!func || !Function::returnsReference(func, true))
1155+
return false;
1156+
const std::vector<const Token*> returns = Function::findReturns(func);
1157+
return std::any_of(returns.begin(), returns.end(), [var](const Token* tok) {
1158+
return tok->varId() == var->declarationId();
1159+
});
1160+
}
1161+
11521162
void CheckUnusedVar::checkFunctionVariableUsage()
11531163
{
11541164
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->checkLibrary && !mSettings->isPremiumEnabled("unusedVariable"))
@@ -1364,7 +1374,9 @@ void CheckUnusedVar::checkFunctionVariableUsage()
13641374
}
13651375
// variable has been read but not written
13661376
else if (!usage._write && !usage._allocateMemory && var && !var->isStlType() && !isEmptyType(var->type()) &&
1367-
!(var->type() && var->type()->needInitialization == Type::NeedInitialization::False))
1377+
!(var->type() && var->type()->needInitialization == Type::NeedInitialization::False) &&
1378+
!(var->valueType() && var->valueType()->container) &&
1379+
!(var->isStatic() && isReturnedByRef(var, scope->function)))
13681380
unassignedVariableError(usage._var->nameToken(), varname);
13691381
else if (!usage._var->isMaybeUnused() && !usage._modified && !usage._read && var) {
13701382
const Token* vnt = var->nameToken();

test/cfg/qt.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,3 +790,9 @@ void constVariablePointer_QVector(QVector<int*>& qv, int* p)
790790
{
791791
qv.push_back(p); // #12661
792792
}
793+
794+
const QString& unassignedVariable_static_QString() // #12935
795+
{
796+
static QString qs;
797+
return qs;
798+
}

test/testunusedvar.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5887,6 +5887,16 @@ class TestUnusedVar : public TestFixture {
58875887
" return k;\n"
58885888
"}\n");
58895889
ASSERT_EQUALS("", errout_str());
5890+
5891+
functionVariableUsage("int& f() {\n" // #12935
5892+
" static int i;\n"
5893+
" return i;\n"
5894+
"}\n"
5895+
"int* g() {\n"
5896+
" static int j;\n"
5897+
" return &j;\n"
5898+
"}\n");
5899+
ASSERT_EQUALS("", errout_str());
58905900
}
58915901

58925902
void localvarextern() {

0 commit comments

Comments
 (0)