有没有一种有效的方法可以按值返回自我分配值?

输出参数通常的cpp建议是:“避免通过可修改的引用传递输出参数,而应按值返回”。现在,如果有一种情况,我们想要修改对象本身,例如

string s = "whatever";
//maybe in a loop
s = modify(s);

Then it looks like a function string modify (string) is always outperformed by a function like modifyInPlace(string &). Is there any way around this problem? Is there any fundamental reason why this can never be solved? I think the semantics of take by value, return by value are safer and clearer.

Example comparison measurement: http://quick-bench.com/-XZqOZw-X739tlcOI8vau8DU24w

评论
  • 买依薇
    买依薇 回复

    Modifying by reference will almost always be faster than modifying by value, unless your values are very small in size (e.g. an int). This is because, when you modify by value, you have to create a copy of the value in memory to pass to the function, while references don't have to do that.