【问题标题】:Proper usage/modification of QString given that some functions are const and others non-const鉴于某些函数是 const 而其他函数是非 const,正确使用/修改 QString
【发布时间】:2013-04-12 19:00:26
【问题描述】:

我正在对 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() 是处理这种情况的正确方法吗?这会实现我的目标,即为下一次使用修剪副本()吗?有没有更好(更优雅、更高效、更 Qtish)的方法来做到这一点?

我已经检查了QString Qt Documentation 并不能令人满意地回答这些问题。

【问题讨论】:

  • qt-project.org/doc/qt-4.8/qstring.html#simplified看来,一旦你使用QString::simplified(),你就不需要使用QString::trimmed()了。
  • @E.M.我需要删除“foo:”和下一段文本之间的任何空格。在调用QString::simplified() 之后,应该限制为一个空间,但我仍然需要删除该空间。我可以先打电话给QString::remove(),但这会弄乱我的原件,而不是给我一份副本:-O
  • 啊,是的,我明白你的意思了。

标签: c++ qt qt4 constants qstring


【解决方案1】:

我认为答案只是出于优化原因。

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

当它们返回对修改后的字符串的引用以获得最终结果时,我经常会添加几个不同的。 (更优雅的方式...)

例如:

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

这里有更多关于隐式共享的内容:

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

希望对您有所帮助。

【讨论】:

  • 我认为优化问题是有意义的,因为隐式共享不一定适用于QString::remove(),但它始终适用于QString::trimmed()。另一方面,如果这是真的,那么QString::simplified() 将不是 const,因为隐式共享可能不起作用。不错的理论,但很可能是原因。谢谢!
  • str = str.toLower().trimmed().simplified();合适吗?
猜你喜欢
  • 2011-11-09
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多