[Development] QLatin1Constant and QtContacts / QtOrganizer

Thiago Macieira thiago.macieira at intel.com
Tue Dec 20 13:17:20 CET 2011


On Monday, 19 de December de 2011 23.08.11, Mathias Hasselmann wrote:
> +1 - QLatin1String is painful to use: You cannot really store references
> to it, you constantly get trouble from C++ not being able to resolve
> which of its cast operators shall be used (QString vs. QLatin1String).
> Also I never really got is purpose: To enable comparison and hashing of
> QtContact's string keys, and to make sure those strings don't waste
> memory on heap, it would have been sufficient to use QString::
> fromRawData() to initialize those constants.

When to use:

QString::fromRawData:

* You already have the data in UTF-16 format
* You can guarantee that the lifetime of said data is longer than the lifetime 
of the QString and all its implicit copies

QLatin1String:

* Your string is in Latin 1 (if your source code is in UTF-8, then your string 
is in US-ASCII)
* You're calling a method in QString that *does* have a QLatin1String overload
* And it's not the QString constructor

QStringLiteral:

* It's a string literal in your source code (it MUST be a literal)
* You're going to use it where only a QString serves, like calling methods 
that take QString or you're creating a QString object

QString::fromXXX and QTextCodec::toUnicode:

* All other cases where either the encoding doesn't match above and you need 
to create a QString copy.


You could use QLatin1String with a non-literal in the same way you'd use 
QString::fromRawData.

That is, such as this:

	QString str = QString::fromLatin1(latin1data);
	QString str = QLatin1String(latin1data);

The difference is that QLatin1String will make an inline call to 
strlen(latin1data), which the compiler may be able to optimise. Then again, we 
could make the same in QString::fromLatin1... any takers?


Do not do this:

	if (str == QStringLiteral("latin 1 string literal"))
		reason: QStringLiteral takes strlen(data) + 18 bytes more space
		use: QLatin1String

	str = QString::fromLatin1("%1 %2").arg(foo, bar);
		reason: QString::fromLatin1 will need to allocate memory
		use: QStringLiteral

	QImage f(QLatin1String("foo.png"));
		reason: will allocate memory for something that doesn't change
		use: QStringLiteral

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center
     Intel Sweden AB - Registration Number: 556189-6027
     Knarrarnäsgatan 15, 164 40 Kista, Stockholm, Sweden
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/development/attachments/20111220/a02fbfe1/attachment.sig>


More information about the Development mailing list