考虑到一些函数是const而另一些函数是非const, QString的正确使用/修改

Proper usage/modification of QString given that some functions are const and others non-const

本文关键字:函数 const 修改 是非 考虑到 QString      更新时间:2023-10-16

我正在对QString执行一些操作以减少它,但我不想影响原始字符串。我是Qt的新手,我对使用各种QString函数的正确方法感到困惑,因为有些是const,而有些则不是。到目前为止,这是我所拥有的:

// this needs to be const so it doesn't get modified.
// code later on is depending on this QString being unchanged
const QString string = getString();

我需要调用的方法是QString::simplified()QString::remove()QString::trimmed()。令人困惑的部分是什么是正确的方法来做到这一点,simplified()trimmed()const,但remove()不是。请记住,我要复制原件并直接对副本进行修改,这是我的:

// simplified() is a const function but no problem because I want a copy of it
QString copy = string.simplified(); 
// remove is non-const so it operates on the handle object, which is what I want
copy.remove( "foo:", Qt::CaseInsensitive );
// trimmed() is const, but I want it to affect the original
copy = copy.trimmed();

使用copy = copy.trimmed()是处理这种情况的正确方法吗?这将实现我的目标,让copy被修剪()为下一次使用吗?有没有更好的(更优雅、更高效、更英伦的)方法来做到这一点?

我已经检查了QString Qt文档,无法令人满意地回答这些问题。

我认为答案很简单,因为优化的原因。

在幕后,QString使用隐式共享(写时复制)来减少内存使用并避免不必要的数据复制。这也有助于减少存储16位字符而不是8位字符的固有开销。

通常,当它们返回对修改字符串的引用以获得最终结果时,我会添加一些不同的参数。(更优雅的方式…)

例如:

QString str = " Hello   Worldn!";
QString str2 = str.toLower().trimmed().simplified();
if(str2.contains("world !"))
{
    qDebug() << str2 << "contains "world !"";
}

这里有更多关于隐式共享的信息:

http://qt project.org/doc/qt - 4.8 -/-隐式- sharing.html

希望对你有帮助。