简体   繁体   English

什么时候使用const string&与const string比较好

[英]When is it better to use const string& versus const string

I understand that it is better to pass const String references as arguments to methods. 我知道最好将const字符串引用作为参数传递给方法。

However, if I just need to use a String as a constant in the code, is it still better to reference it? 但是,如果我只需要在代码中使用String作为常量,那么引用它仍然更好吗? Isn't it just an overhead to get a reference to it? 引用不是唯一的开销吗? I can see this in a number of places in our code base and I'm trying to understand why this would be desirable. 我可以在我们的代码库中的很多地方看到这一点,并且我试图理解为什么这是理想的。

string bar = "test";
const string& data = "FOO_" + bar; //why is this better than const string data?
insert(data)

The function insert takes a reference, 函数插入有一个参考,

void insert(const string& data)

The same question would apply to any const object being used in the same fashion. 相同的问题将适用于以相同方式使用的任何const对象。

Thanks! 谢谢!

A reference in C++ should be thought of as an alias for an existing variable. 应该将C ++中的引用视为现有变量的别名。 You use a reference when you have a variable that already exists that you would like to access by a different alias (name). 当您有一个已经存在的变量并希望通过其他别名(名称)访问时,可以使用引用。

This is most common in function calls when you would like to refer to an existing variable (memory location) as an argument to a function. 当您想将现有变量(内存位置)作为函数的参数引用时,这在函数调用中最为常见。 If you do not want to pass a copy to the function, and you instead want to pass an already existing variable to the function under a new name that is when you use a reference. 如果您不想将副本传递给该函数,而是想使用一个新名称(即使用引用时)将一个已经存在的变量传递给该函数。

Similarly, when you want a class to refer to a variable that already exists you use a reference. 同样,当您希望类引用一个已经存在的变量时,可以使用引用。

A reference 'should' always refer to an existing variable. 引用“应该”始终引用现有变量。

const string data = "FOO_" + bar;

Creates a temporary and passes her as argument to the copy ctor of data on construction. 创建一个临时文件,并将其作为参数传递给构造data副本。 Creates two string instances, does a copy and destructs one instance. 创建两个字符串实例,进行复制并销毁一个实例。

const string& data = "FOO_" + bar;

Creates a temporary but assigns her to name data , so she isn't temporary anymore. 创建一个临时文件,但将其分配给name data ,因此她不再是临时文件。 One instance created, not more. 创建了一个实例,没有更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM