将参数作为 std::string 或 const std::string& 传递? [英] Pass arguments as std::string or const std::string&?

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

问题描述

可能的重复:
在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?

显然 path 永远不会在 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?

推荐答案

在您的情况下,规范的答案是通过 const& 传递参数,这都是出于性能原因(保证避免复制字符串)并且因为您记录了意图.前者仅在您分析代码并确定传递字符串是瓶颈时才重要 - 如果不是,您主要是在查看最佳实践"而不是产生很大的性能差异.

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.

但是对我来说,如果我查看您的函数的签名,第二个明确指出我只会读取您的参数而不对其进行任何操作",而第一个几乎说明您将做某事到参数,即使您在处理参数的副本时外部不会看到您的更改.

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).

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

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