为什么Qt QString的替换方法会改变QString?

Why does Qt QString's replace method mutate the QString?

本文关键字:QString 改变 方法 替换 Qt 为什么      更新时间:2023-10-16

我在当前的Qt代码中使用了许多const QString&对象。替换字符串的某些部分在不同上下文中的大量QString中很常见。不幸的是,Qt使replace方法突变了所属的QString(请参阅http://doc.qt.io/qt-5/qstring.html#replace)。

我经常发现自己需要这样做:

// (note that mClass->DType() returns a `const QString&`)
QString modifiedName = mClass->DType();
modifiedName.replace("*", "");
SomeOtherFunction(modifiedName); 

而不是这个(AFAIK不会工作(:

// (note that mClass->DType() returns a `const QString&`)
SomeOtherFunction(mClass->DType().replace("*", ""));

有更好的方法吗?为什么QString的replace方法会改变QString?

将常量分配给非常量对象。就像你可以把一个非常数分配给一个常量一样。有些API不喜欢这样,但Qt并不挑剔。