Skip to content

Commit

Permalink
Fix #12608 FP returnByReference for virtual function (#6272)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrchr-github committed Apr 11, 2024
1 parent b9c535c commit 5879f28
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
4 changes: 4 additions & 0 deletions lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3327,9 +3327,13 @@ void CheckClass::checkReturnByReference()
for (const Function& func : classScope->functionList) {
if (Function::returnsPointer(&func) || Function::returnsReference(&func) || Function::returnsStandardType(&func))
continue;
if (func.isImplicitlyVirtual())
continue;
if (const Variable* var = getSingleReturnVar(func.functionScope)) {
if (!var->valueType())
continue;
if (var->isArgument())
continue;
const bool isContainer = var->valueType()->type == ValueType::Type::CONTAINER && var->valueType()->container;
const bool isView = isContainer && var->valueType()->container->view;
bool warn = isContainer && !isView;
Expand Down
39 changes: 26 additions & 13 deletions test/testclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8922,21 +8922,34 @@ class TestClass : public TestFixture {
}

void returnByReference() {
checkReturnByReference("struct T { int a[10]; };" // #12546
"struct S {"
" T t;"
" int i;"
" std::string s;"
" T getT() const { return t; }"
" int getI() const { return i; }"
" std::string getS() const { return s; }"
" unknown_t f() { return; }"
"};");
ASSERT_EQUALS("[test.cpp:1]: (performance) Function 'getT()' should return member 't' by const reference.\n"
"[test.cpp:1]: (performance) Function 'getS()' should return member 's' by const reference.\n",
checkReturnByReference("struct T { int a[10]; };\n" // #12546
"struct S {\n"
" T t;\n"
" int i;\n"
" std::string s;\n"
" T getT() const { return t; }\n"
" int getI() const { return i; }\n"
" std::string getS() const { return s; }\n"
" unknown_t f() { return; }\n"
"};\n");
ASSERT_EQUALS("[test.cpp:6]: (performance) Function 'getT()' should return member 't' by const reference.\n"
"[test.cpp:8]: (performance) Function 'getS()' should return member 's' by const reference.\n",
errout_str());
}

checkReturnByReference("struct B {\n" // #12608
" virtual std::string f() { return \"abc\"; }\n"
"};\n"
"struct D : B {\n"
" std::string f() override { return s; }\n"
" std::string s;\n"
"};\n");
ASSERT_EQUALS("", errout_str());

checkReturnByReference("struct S {\n"
" std::string f(std::string s) { return s; }\n"
"};\n");
ASSERT_EQUALS("", errout_str());
}
};

REGISTER_TEST(TestClass)

0 comments on commit 5879f28

Please sign in to comment.