QLatin1String与QString

本文讨论了在Qt中使用QLatin1String类来提高处理常量拉丁1字符串的效率,避免了不必要的字符串复制和深拷贝,从而提升了应用性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal.

Many of QString's member functions are overloaded to accept const char * instead of QString. This includes the copy constructor, the assignment operator, the comparison operators, and various other functions such as insert(), replace(), and indexOf(). These functions are usually optimized to avoid constructing a QStringobject for the const char * data. For example, assuming str is a QString,

if (str == "auto" || str == "extern"
         || str == "static" || str == "register") {
     ...
 }

is much faster than

if (str == QString("auto") || str == QString("extern")
         || str == QString("static") || str == QString("register")) {
     ...
 }

because it doesn't construct four temporary QString objects and make a deep copy of the character data.

Applications that define QT_NO_CAST_FROM_ASCII (as explained in the QString documentation) don't have access to QString's const char * API. To provide an efficient way of specifying constant Latin-1 strings, Qt provides the QLatin1String, which is just a very thin wrapper around a const char *. Using QLatin1String, the example code above becomes

if (str == QLatin1String("auto")
         || str == QLatin1String("extern")
         || str == QLatin1String("static")
         || str == QLatin1String("register") {
     ...
 }

This is a bit longer to type, but it provides exactly the same benefits as the first version of the code, and is faster than converting the Latin-1 strings usingQString::fromLatin1().

Thanks to the QString(const QLatin1String &) constructor, QLatin1String can be used everywhere a QString is expected. For example:

QLabel *label = new QLabel(QLatin1String("MOD"), this);


From:Qt Reference Document

转载于:https://my.oschina.net/xiangxw/blog/16165

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值