qstring-unneeded-heap-allocations
May 13, 2019 ยท View on GitHub
Finds places with unneeded memory allocations due to temporary QStrings.
Here's a summary of usages that allocate:
-
QString s = "foo"; // Allocates, use QStringLiteral("foo") instead -
QString s = QLatin1String("foo"); // Allocates, use QStringLiteral("foo") instead2.1
QString s = QLatin1String(""); // No allocation. QString is optimized for this case, so it's safe for empty literals -
QString s = QStringLiteral("foo"); // No allocation -
QString s = QString::fromLatin1("foo"); // Allocates, use QStringLiteral -
QString s = QString::fromUtf8("foo"); // Allocates, use QStringLiteral -
s == "foo" // Allocates, use QLatin1String -
s == QLatin1String("foo") // No allocation -
s == QStringLiteral("foo") // No allocation -
QString {"append", "compare", "endsWith", "startsWith", "indexOf", "insert","lastIndexOf", "prepend", "replace", "contains" } // They all have QLatin1String overloads, so passing a QLatin1String is ok. -
QString::fromLatin1("foo %1").arg(bar) // Allocates twice, replacing with QStringLiteral makes it allocate only once.
Fixits
This check supports a fixit to rewrite your code. See the README.md on how to enable it.
Pitfalls
-
QStringLiteralmight make your app crash at exit if plugins are involved. See: https://blogs.kde.org/2015/11/05/qregexp-qstringliteral-crash-exit and http://lists.qt-project.org/pipermail/development/2015-November/023681.html -
Also note that MSVC crashes when
QStringLiteralis used inside initializer lists. For that reason no warning or fixit is emitted for this case unless you set an env variable:export CLAZY_EXTRA_OPTIONS="qstring-allocations-no-msvc-compat"