diff --git a/cfg/cppcheck-cfg.rng b/cfg/cppcheck-cfg.rng index a54c967aaac..c24dea3e9dd 100644 --- a/cfg/cppcheck-cfg.rng +++ b/cfg/cppcheck-cfg.rng @@ -595,6 +595,20 @@ + + + + + + + + + + + + + + diff --git a/cfg/qt.cfg b/cfg/qt.cfg index 6a7b2f6704f..dcd56cc1d72 100644 --- a/cfg/qt.cfg +++ b/cfg/qt.cfg @@ -5414,6 +5414,137 @@ QSemaphore QReadWriteLock + + + QBitArray + QBitmap + QBrush + QByteArray + QByteArrayList + QByteArrayView + + QCollator + QCollatorSortKey + QCommandLineOption + QContiguousCache + QCursor + QDBusPendingCall + QDBusUnixFileDescriptor + QDateTime + QDebug + QDir + QDnsDomainNameRecord + QDnsHostAddressRecord + QDnsMailExchangeRecord + QDnsServiceRecord + QDnsTextRecord + QDnsTlsAssociationRecord + QFileInfo + QFont + QFontInfo + QFontMetrics + QFontMetricsF + QFontVariableAxis + + QFormDataPartBuilder + QGeoAreaMonitorInfo + QGeoPositionInfo + QGeoSatelliteInfo + QGlyphRun + QGradient + QHash + QHostAddress + QHttp1Configuration + QHttp2Configuration + QHttpPart + QIcon + QImage + QJsonArray + + QJsonObject + QJsonParseError + QJsonValue + QKeySequence + QLinkedList + QList + QLocale + QLowEnergyAdvertisingData + QLowEnergyAdvertisingParameters + QLowEnergyCharacteristicData + QLowEnergyConnectionParameters + QLowEnergyDescriptorData + QLowEnergyServiceData + QMap + QMimeType + QMqttTopicFilter + QMqttTopicName + QMultiHash + QMultiMap + + QNetworkCacheMetaData + QNetworkCookie + QNetworkInterface + QNetworkProxy + QNetworkProxyQuery + QNetworkRequest + QNetworkRequestFactory + QOpenGLDebugMessage + QPageRanges + QPalette + QPen + QPersistentModelIndex + QPicture + QPixmap + QPolygon + QPolygonF + QProcessEnvironment + QQueue + QRawFont + QRegExp + QRegion + QRegularExpression + QRegularExpressionMatch + QRegularExpressionMatchIterator + QSet + QShader + QSqlField + QSqlQuery + QSqlRecord + QSslCertificate + QSslCertificateExtension + + QSslConfiguration + QSslDiffieHellmanParameters + + QSslKey + QSslPreSharedKeyAuthenticator + QStack + QStaticText + QStorageInfo + QString + QStringList + QTextBlockFormat + + QTextCharFormat + QTextCursor + QTextDocumentFragment + QTextFormat + QTextFrameFormat + QTextImageFormat + QTextListFormat + QTextTableCellFormat + QTextTableFormat + QUrl + QUrlQuery + + + QVariant + + QVector + diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 1bc1ea1fcd9..3b54932466f 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -3641,6 +3641,35 @@ void CheckClassImpl::checkReturnByReference() continue; if (var->isArgument()) continue; + // Prefer the resolved scope to distinguish unrelated types with + // the same unqualified name as a configured library type. + std::string qualifiedTypeName = var->getTypeName(); + if (const Scope* typeScope = var->typeScope()) { + qualifiedTypeName.clear(); + for (const Scope* scope = typeScope; scope && scope->type != ScopeType::eGlobal; scope = scope->nestedIn) { + if (scope->className.empty()) { + qualifiedTypeName.clear(); + break; + } + qualifiedTypeName = scope->className + (qualifiedTypeName.empty() ? "" : "::" + qualifiedTypeName); + } + } + // Instantiated templates can be represented by a single token. + // Match the configured type name without template arguments. + std::string typeName; + int templateDepth = 0; + for (char c : qualifiedTypeName) { + if (c == '<') + ++templateDepth; + else if (c == '>') + --templateDepth; + else if (templateDepth == 0 && c != ' ') + typeName += c; + } + if (typeName.compare(0, 2, "::") == 0) + typeName.erase(0, 2); + if (mSettings.library.getTypeCheck("returnByReference", typeName) == Library::TypeCheck::suppress) + 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; diff --git a/man/checkers/returnByReference.md b/man/checkers/returnByReference.md index 8909020f844..a60af45248b 100644 --- a/man/checkers/returnByReference.md +++ b/man/checkers/returnByReference.md @@ -12,10 +12,16 @@ on every call, when it could return a `const` reference instead. ## Motivation -Returning a container or string by value copies its entire contents on every call, even though the +Returning a deep-copying container or string by value copies its contents on every call, even though the caller almost always just wants to look at the member that's already sitting inside the object. Returning a `const&` instead avoids that copy entirely. +Implicitly shared types can make cheap shallow copies instead. Library configurations can +suppress this check for such types using ``; +the Qt configuration does this for common implicitly shared strings, containers and image types. +Before changing a getter to return a reference, consider the required snapshot semantics and +whether callers could outlive the object or invalidate the referenced member. + ## How to fix Before: diff --git a/man/reference-cfg-format.md b/man/reference-cfg-format.md index 596fd6cb856..f41fcf25eb1 100644 --- a/man/reference-cfg-format.md +++ b/man/reference-cfg-format.md @@ -536,6 +536,20 @@ Example: In the `unusedvar` checking the `foo` type will be checked. Warnings for `bar` type variables will be suppressed. +The `returnByReference` check also supports type-specific suppression. For example, +an implicitly shared type can be returned by value without copying its contents: + + + + MySharedValue + + + +This suppresses `returnByReference` for members of type `MySharedValue` without +disabling the check for other types. For templates, use the type name without +template arguments, such as `MySharedContainer`. Use qualified names for types +declared in a namespace, such as `MyNamespace::MySharedValue`. + # `` Libraries can be used to define preprocessor macros as well. For example: diff --git a/test/testclass.cpp b/test/testclass.cpp index 4449e368561..d0f79fc8068 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -264,6 +264,12 @@ class TestClass : public TestFixture { TEST_CASE(testGetFileInfo); TEST_CASE(returnByReference); + TEST_CASE(returnByReferenceTypeChecks); + TEST_CASE(returnByReferenceQt); + TEST_CASE(returnByReferenceQtSharedValues); + TEST_CASE(returnByReferenceQtContainers); + TEST_CASE(returnByReferenceGlobalQualification); + TEST_CASE(returnByReferenceScopedTypes); } #define checkCopyCtorAndEqOperator(...) checkCopyCtorAndEqOperator_(__FILE__, __LINE__, __VA_ARGS__) @@ -9480,7 +9486,11 @@ class TestClass : public TestFixture { template void checkReturnByReference_(const char* file, int line, const char (&code)[size]) { const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").build(); + checkReturnByReference_(file, line, code, settings); + } + template + void checkReturnByReference_(const char* file, int line, const char (&code)[size], const Settings& settings) { SimpleTokenizer2 tokenizer(settings, *this, code, "test.cpp"); ASSERT_LOC(tokenizer.simplifyTokens1(""), file, line); @@ -9490,6 +9500,175 @@ class TestClass : public TestFixture { (checkClass.checkReturnByReference)(); } + void returnByReferenceTypeChecks() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").libraryxml( + "" + "Shared" + "shared::Value" + "Expensive" + "").build(); + checkReturnByReference("struct Shared { int data[10]; };\n" + "struct Expensive { int data[10]; };\n" + "struct S {\n" + " Shared shared;\n" + " Expensive expensive;\n" + " Shared getShared() const { return shared; }\n" + " Expensive getExpensive() const { return expensive; }\n" + "};\n", settings); + ASSERT_EQUALS("[test.cpp:7:15]: (performance) Function 'getExpensive()' should return member 'expensive' by const reference. [returnByReference]\n", + errout_str()); + + checkReturnByReference("namespace shared { template struct Value { T data[10]; }; }\n" + "using Alias = shared::Value;\n" + "struct S {\n" + " const Alias value;\n" + " Alias getValue() const { return value; }\n" + "};\n", settings); + ASSERT_EQUALS("", errout_str()); + } + + void returnByReferenceQt() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").library("qt.cfg").build(); + checkReturnByReference("struct S {\n" + " QString string;\n" + " QByteArray bytes;\n" + " QList list;\n" + " std::string expensive;\n" + " QString getString() const { return string; }\n" + " QByteArray getBytes() const { return bytes; }\n" + " QList getList() const { return list; }\n" + " std::string getExpensive() const { return expensive; }\n" + "};\n", settings); + ASSERT_EQUALS("[test.cpp:9:17]: (performance) Function 'getExpensive()' should return member 'expensive' by const reference. [returnByReference]\n", + errout_str()); + + // Non-container shared types must also bypass the object-size heuristic. + checkReturnByReference("struct QImage { int data[10]; };\n" + "struct S {\n" + " QImage image;\n" + " QImage getImage() const { return image; }\n" + "};\n", settings); + ASSERT_EQUALS("", errout_str()); + + checkReturnByReference("using String = QString;\n" + "struct S {\n" + " const String string;\n" + " QStringList list;\n" + " String getString() const { return string; }\n" + " QStringList getList() const { return list; }\n" + "};\n", settings); + ASSERT_EQUALS("", errout_str()); + + checkReturnByReference("template struct QList { T data[10]; };\n" + "struct S {\n" + " QList list;\n" + " QList getList() const { return list; }\n" + "};\n", settings); + ASSERT_EQUALS("", errout_str()); + } + + void returnByReferenceQtSharedValues() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").library("qt.cfg").build(); + // Model non-container value types as large objects to exercise the size heuristic. + checkReturnByReference("struct QUrl { int data[10]; };\n" + "struct QDateTime { int data[10]; };\n" + "struct QVariant { int data[10]; };\n" + "struct QJsonObject { int data[10]; };\n" + "struct QNetworkRequest { int data[10]; };\n" + "struct QTextCursor { int data[10]; };\n" + "struct QTextBoundaryFinder { int data[10]; };\n" + "struct S {\n" + " QUrl url;\n" + " QDateTime dateTime;\n" + " QVariant variant;\n" + " QJsonObject json;\n" + " QNetworkRequest request;\n" + " QTextCursor cursor;\n" + " QTextBoundaryFinder boundaryFinder;\n" + " QUrl getUrl() const { return url; }\n" + " QDateTime getDateTime() const { return dateTime; }\n" + " QVariant getVariant() const { return variant; }\n" + " QJsonObject getJson() const { return json; }\n" + " QNetworkRequest getRequest() const { return request; }\n" + " QTextCursor getCursor() const { return cursor; }\n" + " QTextBoundaryFinder getBoundaryFinder() const { return boundaryFinder; }\n" + "};\n", settings); + ASSERT_EQUALS("[test.cpp:22:25]: (performance) Function 'getBoundaryFinder()' should return member 'boundaryFinder' by const reference. [returnByReference]\n", + errout_str()); + } + + void returnByReferenceQtContainers() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").library("qt.cfg").build(); + checkReturnByReference("template struct QList { T data[10]; };\n" + "template struct QStack { T data[10]; };\n" + "template struct QQueue { T data[10]; };\n" + "template struct QSet { T data[10]; };\n" + "template struct QMap { T data[10]; };\n" + "template struct QMultiMap { T data[10]; };\n" + "template struct QHash { T data[10]; };\n" + "template struct QMultiHash { T data[10]; };\n" + "template struct QContiguousCache { T data[10]; };\n" + "template struct QVarLengthArray { T data[10]; };\n" + "struct S {\n" + " QList list;\n" + " QStack stack;\n" + " QQueue queue;\n" + " QSet set;\n" + " QMap> map;\n" + " QMultiMap multiMap;\n" + " QHash hash;\n" + " QMultiHash multiHash;\n" + " QContiguousCache cache;\n" + " QVarLengthArray array;\n" + " QList getList() const { return list; }\n" + " QStack getStack() const { return stack; }\n" + " QQueue getQueue() const { return queue; }\n" + " QSet getSet() const { return set; }\n" + " QMap> getMap() const { return map; }\n" + " QMultiMap getMultiMap() const { return multiMap; }\n" + " QHash getHash() const { return hash; }\n" + " QMultiHash getMultiHash() const { return multiHash; }\n" + " QContiguousCache getCache() const { return cache; }\n" + " QVarLengthArray getArray() const { return array; }\n" + "};\n", settings); + ASSERT_EQUALS("[test.cpp:31:26]: (performance) Function 'getArray()' should return member 'array' by const reference. [returnByReference]\n", + errout_str()); + } + + void returnByReferenceGlobalQualification() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").library("qt.cfg").build(); + checkReturnByReference("struct S {\n" + " ::QString string;\n" + " ::QList list;\n" + " ::QString getString() const { return string; }\n" + " ::QList getList() const { return list; }\n" + "};\n", settings); + ASSERT_EQUALS("", errout_str()); + } + + void returnByReferenceScopedTypes() { + const Settings settings = settingsBuilder().severity(Severity::performance).library("std.cfg").library("qt.cfg").build(); + checkReturnByReference("namespace N {\n" + " struct QString { int data[10]; };\n" + " struct S {\n" + " QString string;\n" + " QString getString() const { return string; }\n" + " };\n" + "}\n", settings); + ASSERT_EQUALS("[test.cpp:5:17]: (performance) Function 'getString()' should return member 'string' by const reference. [returnByReference]\n", + errout_str()); + + checkReturnByReference("namespace {\n" + " struct QImage { int data[10]; };\n" + " struct S {\n" + " QImage image;\n" + " QImage getImage() const { return image; }\n" + " };\n" + "}\n", settings); + ASSERT_EQUALS("[test.cpp:5:16]: (performance) Function 'getImage()' should return member 'image' by const reference. [returnByReference]\n", + errout_str()); + } + void returnByReference() { checkReturnByReference("struct T { int a[10]; };\n" // #12546 "struct S {\n"