简体   繁体   English

如何在const&参数上使用QString :: replace?

[英]How to use QString::replace on a const& parameter?

What is the best way to call QString::replace in a non-destructive way ? 以非破坏性方式调用QString::replace的最佳方法是什么?

I have a function taking a const QString& as a parameter, then I can't directly call call replace because this function modify the object (same for remove ). 我有一个将const QString&作为参数的函数,所以我不能直接调用调用replace因为此函数会修改对象(与remove相同)。
I would like to chain calls on the parameter and to use that as an expression like : 我想在参数上链接调用,并将其用作表达式:

return myString.replace(QRegExp("\\s+"), "_").remove("someSuffix");

Of course I could change the function definition to take the QString by value instead of reference, but I don't like this solution. 当然,我可以更改函数定义以按值而不是引用采用QString,但是我不喜欢这种解决方案。 One could later wonder why we are not passing by reference like the rest of the parameters. 后来人们可能想知道为什么我们不像其他参数那样通过引用传递。

I can also make a local copy but is there any more practical/clean way ? 我也可以制作本地副本,但是还有其他实用/干净的方法吗?

You can create a temporary and operate on it: 您可以创建一个临时文件并对其进行操作:

return QString(argument).replace(QRegExp("\\s+"), "_").remove("someSuffix");

However, I don't see anything bad in accepting the argument by value. 但是,我认为按值接受参数没有什么不好。 You are copying the argument in one way or another, and acepting by value clearly indicates this to the user. 您正在以一种或另一种方式复制自变量,并且按值接受显然会向用户表明这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 函数获取参数的生命周期扩展由const&和const返回 - lifetime extension for function taking parameter by const& and returning by const& 错误:未定义对MainWindow :: on_Input_A_textChanged(QString const&)的引用 - error: undefined reference to `MainWindow::on_Input_A_textChanged(QString const&)' QString :: replace(const QRegExp&,const QString&)和QString :: replace(const QRegularExpression&,const QString&)的工作方式不同 - QString::replace(const QRegExp &, const QString &) and QString::replace(const QRegularExpression &, const QString &) work differently 为STL定义函子时,为什么必须使用const&参数? - Why must I use a const& parameter when defining a functor for STL? 是否使用T const&或T &amp;&amp; - Whether to use T const& or T&& 什么时候应该使用const&? - When should I use const& to this? std::string const&amp; 参数是否复制传递的 const char*? - Does std::string const& parameter copies the passed const char*? moc_kviz.cpp:72: 错误:未定义对`Kviz::on_lineEdit_textChanged(QString const&amp;)&#39;的引用 - moc_kviz.cpp:72: error: undefined reference to `Kviz::on_lineEdit_textChanged(QString const&)' 如何使用QMap <QString, QString> :: const_iterator作为指针? - How can I use a QMap<QString, QString>::const_iterator as a pointer? 模板参数包无法推断`const&`参数 - Template parameter pack can't infer `const&` argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM