The macro generates the data for a QString out of the string literal str at compile time. Creating a QString from it is free in this case, and the generated string data is stored in the read-only segment of the compiled object file。
使用QStringLiteral宏可以在编译期把代码里的常量字符串str直接构造为QString对象,于是运行时就不再需要额外的构造开销了。
如果编译器支持,则QStringLiteral宏在编译时从str生成一个QString的数据。在这种情况下从 QStringLiteral创建一个QString是自由的,生成的字符串数据存储在编译的目标文件的只读段中;对于不支持的编译器,QStringLiteral的使用效果将与使用QString::fromUtf8() 一样。
If you have code that looks like this:
// hasAttribute takes a QString argument
if (node.hasAttribute("http-contents-length")) //...
then a temporary QString will be created to be passed as the hasAttribute function parameter. This can be quite expensive, as it involves a memory allocation and the copy/conversion of the data into QString’s internal encoding.
这将创建一个临时QString 作为hasAttribute函数的参数传递。这可能是非常耗费资源的,因为它涉及内存分配以及将数据复制和转换为QString的内部编码数据。
This cost can be avoided by using QStringLiteral instead:
if (node.hasAttribute(QStringLiteral(u"http-contents-length"))) //...
In this case, QString’s internal data will be generated at compile time; no conversion or allocation will occur at runtime.
然后,QString 的内部数据将在编译时生成,并且在运行时将不会发生任何的转换或分配。
Using QStringLiteral instead of a double quoted plain C++ string literal can significantly speed up creation of QString instances from data known at compile time.
使用 QStringLiteral 而不是双引号的 ascii 文字可以大大加快从编译时已知的数据中创建 QString 的速度。如果编译器启用了 C++11,则字符串 str 实际上可以包含 unicode 数据。
Note: QLatin1String can still be more efficient than QStringLiteral when the string is passed to a function that has an overload taking QLatin1String and this overload avoids conversion to QString. For instance, QString::operator==() can compare to a QLatin1String directly:
注意:在有一些情况下 QLatin1String 是比 QStringLiteral 更有效的:如果它被传递给一个有直接接受 QLatin1String 而不转换成 QString 类型参数的重载的函数时。 例如,QString::operator == 就是这种情况
if (attribute.name() == QLatin1String("http-contents-length")) //...
Note: Some compilers have bugs encoding strings containing characters outside the US-ASCII character set. Make sure you prefix your string with u in those cases. It is optional otherwise.
//串联字符串文字不能与 QStringLiteral 一起使用。
QString s = QStringLiteral("a" "b");
//QStringLiteral 不能用来初始化 QString 的列表或数组。
QString a[] = { QStringLiteral("a"), QStringLiteral("b") };