[Development] HEADS-UP: QStringLiteral

Mutz, Marc marc at kdab.com
Wed Aug 21 15:34:53 CEST 2019

On 2019-08-21 14:13, Sérgio Martins via Development wrote:
> On 2019-08-20 16:56, Bogdan Vatra via Development wrote:
>> Hi,
>>   Isn't silly to have so many wrappers around a such a simple thing as
>> strings? All the major frameworks out there (i.e. Java, C#) they have 
>> a single
>> String which does all the magic.
> We do have a single one that does all the magic: QString. A Qt user
> can ignore all others.


> The difference between Qt and Java or C# is that we also offer
> non-allocating alternatives for users who care. And if they care, they
> need to learn them.

Another difference is that, in Java at least (or was it JavaScript?), 
"foo" _is_ a String (as in "foo".length()). This is decidedly not the 
case in C++/Qt. In Java, the compiler can place "foo" into read-only 
memory, and it will be an (immutable, as I learned) String instance. 
It's probably also the case that all "foo" in the same program are the 
same string. All this is, or at least may be, also the case for "foo" in 
C++, except that "foo" is not a std::string or QString instance. C++ has 
no concept of strings. Only of string literals. "foo" is a const 
char[4]. To manipulate it, you need to use malloc/strdup/strcpy, or you 
must copy the data into a user-defined class such as std::string or 
QString. We can lament this over and over again, but it will not change 
the facts. QStringLiteral is an attempt at fixing this: a fully-fledged 
QString, but placed in read-only memory, no runtime allocations. The 
problem is that the way it's implemented, QStringLiteral("foo") + 
QStringLiteral("foo") stores the string u"foo" and its QStringData 
header, _twice_ in the executable. And since we globally enabled 
QStringBuilder, there's no runtime efficiency difference to 
QLatin1String("foo") + QLatin1String("foo") which _will_ store "foo" 
just once.

> For the case that triggered this discussion, the androiddeployqt
> executable, I wouldn't bother with optimizations and just use what's
> more readable, even raw strings.

I agree in principle. The problem in Qt code is that it's mostly 
library, and making checkers (and reviewers) aware of the type of source 
code will be extra work compared to just applying the same rules 
everywhere. After all, this is decidedly not optimisation, it's avoiding 
pessimisation, and as such, the non-pessimised version of the code 
should naturally flow from your fingers. It should take extra mental 
work to unlearn the library rules when coding on a tool for once.


Code gets copied: this is from a tool:


this was later found in a plugin:


So while I totally agree that in application code, do as you want, the 
advice is not quite so clear-cut for Qt tools, or, in fact, any project 
where the same developers are working on a library as well as tools.


More information about the Development mailing list