C++ 字符串作为参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14693745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:36:18  来源:igfitidea点击:

string as parameter?

c++stringparametersreference

提问by ofey

If i am not going to modify a string then is the first option better or are both same-(I just want to iterate through the string, but since string size is big I don't want local copy to be made.)

如果我不打算修改字符串,那么第一个选项是更好还是两者相同-(我只想遍历字符串,但由于字符串大小很大,我不希望进行本地复制。)

int getString(string& str1) {
    //code
}


int getString (string str1) {
    //code
}

And if I do plan on changing the string, then is there any difference between the two? Is it because strings are immutable in C++?

如果我确实打算更改字符串,那么两者之间有什么区别吗?是因为字符串在 C++ 中是不可变的吗?

回答by Luchian Grigore

String literals are immutable, std::strings are not.

字符串文字是不可变的,std::strings 不是。

The first one is pass-by-reference. If you don't plan on modifying the string, pass it by constreference.

第一个是按引用传递。如果您不打算修改字符串,请通过const引用传递它。

The second is pass-by-value - if you do modify the string inside the function, you'd only be modifying a copy, so it's moot.

第二个是按值传递——如果你确实修改了函数内的字符串,你只会修改一个副本,所以它没有实际意义。

回答by Luchian Grigore

Why don't you pass by const reference? This way neither will a copy be made, nor will the called function be able to modify the string.

为什么不通过 const 引用?这样既不会复制,也不会被调用的函数能够修改字符串。

int getString(string const &str1)
{
}

回答by slugonamission

Yes, there will be a difference.

是的,会有区别。

The second variant (without the &) will copythe string by value into the scope of the getStringfunction. This means that any updates you make will affect the local copy, not the caller's copy. This is done by calling the class's copy constructor with the old value (std::string(std::string& val)).

第二个变体(没有&)将按值将字符串复制getString函数的作用域中。这意味着您所做的任何更新都会影响本地副本,而不是调用者的副本。这是通过使用旧值 ( std::string(std::string& val))调用类的复制构造函数来完成的。

On the other hand, the first variant (with the &) passes by reference, so changing the local variable will change the caller's variable, unless the reference is marked as const (in which case, you cannot change the value). This shouldbe faster since no copy operation needs to happen if you are not changing the string.

另一方面,第一个变体(带有&)通过引用传递,因此更改局部变量将更改调用者的变量,除非引用标记为 const(在这种情况下,您不能更改值)。这应该更快,因为如果您不更改字符串,则不需要进行复制操作。