传递参数为标准::字符串或const的std ::串放;? [英] Pass arguments as std::string or const std::string&?

查看:114
本文介绍了传递参数为标准::字符串或const的std ::串放;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference\">Is在C ++更好的按值传递或通过不断的引用传递?

我想过这个,而写文件系统。

I thought about this while writing a file system.

vector<string> getFiles(string path);
vector<string> getFiles(const string& path);

什么一个是快?什么人更优雅?

What one is faster? What one is more elegant?

显然路径绝不会在的GetFiles 方法来改变。

Obviously path will never be changed in the getFiles method.

奖励:我使用的是C ++ 11。有没有办法移动语义将加快一切吗?

Bonus: I'm using C++11. Is there a way move semantics would speed everything up?

推荐答案

在您的情况的规范的答案是通过由参数常量和放大器; ,既为原因性能(这是保证,以避免复制字符串),因为你记录的意图的。如果你有你的异形code和确定传递字符串是一个瓶颈,前者是唯一重要的 - 如果不是,你主要是在寻找最佳实践,而不是让一个很大的性能差异

The canonical answer in your situation would be to pass the argument by const&, both for reasons of performance (it is guaranteed to avoid copying the string) and because you document intent. The former is only important if you have profiled your code and determined that passing the string is a bottleneck - if it isn't, you're mostly looking at "best practises" rather than making a big performance difference.

不过对我来说,如果我看看你的函数的签名,第二个明确指出:我将只读取你的参数,而不是对它做任何事情,而第一个pretty很多国家,你会可以做一些参数,即使你是在参数的拷贝工作的更改将不可见到外面。

However to me, if I look at the signature of your function, the second one clearly states "I will only read your parameter and not do anything to it", whereas the first one pretty much states that you will be doing something to the parameter, even though your changes will not be visible to the outside as you are working on a copy of the parameter.

还有一个额外的好处,以const引用传递参数避免了内存分配,如果你不具有无限的存储系统(即,所有的人)的工作是得心应手。

There is also the added advantage that passing the argument by const reference avoids memory allocations, which is handy if you are working on a system that doesn't have infinite memory (ie, all of them).

这篇关于传递参数为标准::字符串或const的std ::串放;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆