[英]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.