Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions cfg/cppcheck-cfg.rng
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,20 @@
</zeroOrMore>
</element>
</optional>
<optional>
<element name="returnByReference">
<zeroOrMore>
<choice>
<element name="check">
<ref name="DATA-EXTNAME"/>
</element>
<element name="suppress">
<ref name="DATA-EXTNAME"/>
</element>
</choice>
</zeroOrMore>
</element>
</optional>
</element>

<element name="podtype">
Expand Down
131 changes: 131 additions & 0 deletions cfg/qt.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -5414,6 +5414,137 @@
<suppress>QSemaphore</suppress>
<suppress>QReadWriteLock</suppress>
</operatorEqVarError>
<!-- Prefer value semantics for implicitly shared and other cheap-copy Qt types.
Based on https://doc.qt.io/qt-6/implicit-sharing.html (Qt 6.12).
Do not infer sharing from Q_DECLARE_SHARED alone since it also marks relocatable types. -->
<returnByReference>
<suppress>QBitArray</suppress>
<suppress>QBitmap</suppress>
<suppress>QBrush</suppress>
<suppress>QByteArray</suppress>
<suppress>QByteArrayList</suppress>
<suppress>QByteArrayView</suppress>
<!-- QCache is noncopyable and is deliberately not suppressed. -->
<suppress>QCollator</suppress>
<suppress>QCollatorSortKey</suppress>
<suppress>QCommandLineOption</suppress>
<suppress>QContiguousCache</suppress>
<suppress>QCursor</suppress>
<suppress>QDBusPendingCall</suppress>
<suppress>QDBusUnixFileDescriptor</suppress>
<suppress>QDateTime</suppress>
<suppress>QDebug</suppress>
<suppress>QDir</suppress>
<suppress>QDnsDomainNameRecord</suppress>
<suppress>QDnsHostAddressRecord</suppress>
<suppress>QDnsMailExchangeRecord</suppress>
<suppress>QDnsServiceRecord</suppress>
<suppress>QDnsTextRecord</suppress>
<suppress>QDnsTlsAssociationRecord</suppress>
<suppress>QFileInfo</suppress>
<suppress>QFont</suppress>
<suppress>QFontInfo</suppress>
<suppress>QFontMetrics</suppress>
<suppress>QFontMetricsF</suppress>
<suppress>QFontVariableAxis</suppress>
<!-- QFormDataBuilder is noncopyable and is deliberately not suppressed. -->
<suppress>QFormDataPartBuilder</suppress>
<suppress>QGeoAreaMonitorInfo</suppress>
<suppress>QGeoPositionInfo</suppress>
<suppress>QGeoSatelliteInfo</suppress>
<suppress>QGlyphRun</suppress>
<suppress>QGradient</suppress>
<suppress>QHash</suppress>
<suppress>QHostAddress</suppress>
<suppress>QHttp1Configuration</suppress>
<suppress>QHttp2Configuration</suppress>
<suppress>QHttpPart</suppress>
<suppress>QIcon</suppress>
<suppress>QImage</suppress>
<suppress>QJsonArray</suppress>
<!-- QJsonDocument allocates a private object when copied and is not suppressed. -->
<suppress>QJsonObject</suppress>
<suppress>QJsonParseError</suppress>
<suppress>QJsonValue</suppress>
<suppress>QKeySequence</suppress>
<suppress>QLinkedList</suppress>
<suppress>QList</suppress>
<suppress>QLocale</suppress>
<suppress>QLowEnergyAdvertisingData</suppress>
<suppress>QLowEnergyAdvertisingParameters</suppress>
<suppress>QLowEnergyCharacteristicData</suppress>
<suppress>QLowEnergyConnectionParameters</suppress>
<suppress>QLowEnergyDescriptorData</suppress>
<suppress>QLowEnergyServiceData</suppress>
<suppress>QMap</suppress>
<suppress>QMimeType</suppress>
<suppress>QMqttTopicFilter</suppress>
<suppress>QMqttTopicName</suppress>
<suppress>QMultiHash</suppress>
<suppress>QMultiMap</suppress>
<!-- QNetworkAddressEntry allocates a private object when copied and is not suppressed. -->
<suppress>QNetworkCacheMetaData</suppress>
<suppress>QNetworkCookie</suppress>
<suppress>QNetworkInterface</suppress>
<suppress>QNetworkProxy</suppress>
<suppress>QNetworkProxyQuery</suppress>
<suppress>QNetworkRequest</suppress>
<suppress>QNetworkRequestFactory</suppress>
<suppress>QOpenGLDebugMessage</suppress>
<suppress>QPageRanges</suppress>
<suppress>QPalette</suppress>
<suppress>QPen</suppress>
<suppress>QPersistentModelIndex</suppress>
<suppress>QPicture</suppress>
<suppress>QPixmap</suppress>
<suppress>QPolygon</suppress>
<suppress>QPolygonF</suppress>
<suppress>QProcessEnvironment</suppress>
<suppress>QQueue</suppress>
<suppress>QRawFont</suppress>
<suppress>QRegExp</suppress>
<suppress>QRegion</suppress>
<suppress>QRegularExpression</suppress>
<suppress>QRegularExpressionMatch</suppress>
<suppress>QRegularExpressionMatchIterator</suppress>
<suppress>QSet</suppress>
<suppress>QShader</suppress>
<suppress>QSqlField</suppress>
<suppress>QSqlQuery</suppress>
<suppress>QSqlRecord</suppress>
<suppress>QSslCertificate</suppress>
<suppress>QSslCertificateExtension</suppress>
<!-- QSslCipher allocates a private object when copied and is not suppressed. -->
<suppress>QSslConfiguration</suppress>
<suppress>QSslDiffieHellmanParameters</suppress>
<!-- QSslError allocates a private object when copied and is not suppressed. -->
<suppress>QSslKey</suppress>
<suppress>QSslPreSharedKeyAuthenticator</suppress>
<suppress>QStack</suppress>
<suppress>QStaticText</suppress>
<suppress>QStorageInfo</suppress>
<suppress>QString</suppress>
<suppress>QStringList</suppress>
<suppress>QTextBlockFormat</suppress>
<!-- QTextBoundaryFinder deep-copies its attributes and is not suppressed. -->
<suppress>QTextCharFormat</suppress>
<suppress>QTextCursor</suppress>
<suppress>QTextDocumentFragment</suppress>
<suppress>QTextFormat</suppress>
<suppress>QTextFrameFormat</suppress>
<suppress>QTextImageFormat</suppress>
<suppress>QTextListFormat</suppress>
<suppress>QTextTableCellFormat</suppress>
<suppress>QTextTableFormat</suppress>
<suppress>QUrl</suppress>
<suppress>QUrlQuery</suppress>
<!-- QVarLengthArray copies its elements and is not suppressed. -->
<!-- QVariant can invoke the copy constructor of an inline value. Its inclusion is a
value-type policy, not a guarantee that every contained type is cheap to copy. -->
<suppress>QVariant</suppress>
<!-- Retain QVector for compatibility with Qt versions where it is not a QList alias. -->
<suppress>QVector</suppress>
</returnByReference>
</type-checks>
<!-- Treat QStringList as QList<QString> since we can't remove the template parameter when we inherit. -->
<define name="QStringList" value="QList&lt;QString&gt;"/>
Expand Down
29 changes: 29 additions & 0 deletions lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
8 changes: 7 additions & 1 deletion man/checkers/returnByReference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<type-checks><returnByReference><suppress>`;
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:
Expand Down
14 changes: 14 additions & 0 deletions man/reference-cfg-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

<type-checks>
<returnByReference>
<suppress>MySharedValue</suppress>
</returnByReference>
</type-checks>

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`.

# `<define>`

Libraries can be used to define preprocessor macros as well. For example:
Expand Down
Loading