如何在 C++ 中使用引用参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2564873/
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
How do I use Reference Parameters in C++?
提问by Sagistic
I am trying to understand how to use reference parameters. There are several examples in my text, however they are too complicated for me to understand why and how to use them.
我试图了解如何使用参考参数。我的课文中有几个例子,但是它们太复杂了,我无法理解为什么以及如何使用它们。
How and why would you want to use a reference? What would happen if you didn't make the parameter a reference, but instead left the &
off?
您想如何以及为什么要使用参考?如果您没有将参数设为引用,而是将其&
关闭,会发生什么?
For example, what's the difference between these functions:
例如,这些函数之间有什么区别:
int doSomething(int& a, int& b);
int doSomething(int a, int b);
I understand that reference variables are used in order to change a formal->reference, which then allows a two-way exchange of parameters. However, that is the extent of my knowledge, and a more concrete example would be of much help.
我知道使用引用变量是为了更改形式->引用,然后允许双向交换参数。然而,这是我的知识范围,一个更具体的例子会很有帮助。
回答by GManNickG
Think of a reference as an alias. When you invoke something on a reference, you're really invoking it on the object to which the reference refers.
将引用视为别名。当您在引用上调用某些内容时,您实际上是在引用所引用的对象上调用它。
int i;
int& j = i; // j is an alias to i
j = 5; // same as i = 5
When it comes to functions, consider:
说到函数,请考虑:
void foo(int i)
{
i = 5;
}
Above, int i
is a value and the argument passed is passed by value. That means if we say:
上面,int i
是一个值,传递的参数是通过value传递的。这意味着如果我们说:
int x = 2;
foo(x);
i
will be a copyof x
. Thus setting i
to 5 has no effect on x
, because it's the copy of x
being changed. However, if we make i
a reference:
i
将是一个复制的x
。因此设置i
为 5 对 没有影响x
,因为它是x
被更改的副本。但是,如果我们做i
一个参考:
void foo(int& i) // i is an alias for a variable
{
i = 5;
}
Then saying foo(x)
no longer makes a copy of x
; i
isx
. So if we say foo(x)
, inside the function i = 5;
is exactly the same as x = 5;
, and x
changes.
然后说foo(x)
不再制作副本x
;i
是x
。所以如果我们说foo(x)
, 里面的函数i = 5;
和 , 完全一样x = 5;
,并且x
发生了变化。
Hopefully that clarifies a bit.
希望这能澄清一点。
Why is this important? When you program, you neverwant to copy and paste code. You want to make a function that does one task and it does it well. Whenever that task needs to be performed, you use that function.
为什么这很重要?编程时,您永远不想复制和粘贴代码。你想创建一个函数来完成一项任务并且它做得很好。每当需要执行该任务时,您就可以使用该功能。
So let's say we want to swap two variables. That looks something like this:
所以假设我们想要交换两个变量。看起来像这样:
int x, y;
// swap:
int temp = x; // store the value of x
x = y; // make x equal to y
y = temp; // make y equal to the old value of x
Okay, great. We want to make this a function, because: swap(x, y);
is much easier to read. So, let's try this:
好的,太好了。我们想让它成为一个函数,因为:swap(x, y);
更容易阅读。所以,让我们试试这个:
void swap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
This won't work! The problem is that this is swapping copiesof two variables. That is:
这行不通!问题在于这是交换两个变量的副本。那是:
int a, b;
swap(a, b); // hm, x and y are copies of a and b...a and b remain unchanged
In C, where references do not exist, the solution was to pass the address of these variables; that is, use pointers*:
在 C 中,引用不存在,解决方案是传递这些变量的地址;也就是说,使用指针*:
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int a, b;
swap(&a, &b);
This works well. However, it's a bit clumsy to use, and actually a bit unsafe. swap(nullptr, nullptr)
, swaps two nothings and dereferences null pointers...undefined behavior! Fixable with some checks:
这很好用。但是,使用起来有点笨拙,实际上有点不安全。swap(nullptr, nullptr)
, 交换两个空指针并取消引用空指针......未定义的行为!可以通过一些检查修复:
void swap(int* x, int* y)
{
if (x == nullptr || y == nullptr)
return; // one is null; this is a meaningless operation
int temp = *x;
*x = *y;
*y = temp;
}
But looks how clumsy our code has gotten. C++ introduces references to solve this problem. If we can just alias a variable, we get the code we were looking for:
但是看起来我们的代码变得多么笨拙。C++ 引入了引用来解决这个问题。如果我们可以给一个变量取别名,我们就会得到我们正在寻找的代码:
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int a, b;
swap(a, b); // inside, x and y are really a and b
Both easy to use, and safe. (We can't accidentally pass in a null, there are no null references.) This works because the swap happening inside the function is really happening on the variables being aliased outside the function.
既易于使用,又安全。(我们不能不小心传入一个空值,没有空引用。)这是有效的,因为函数内部发生的交换实际上发生在函数外部别名的变量上。
(Note, never write a swap
function. :) One already exists in the header <algorithm>
, and it's templated to work with any type.)
(注意,永远不要写一个swap
函数。:) header 中已经存在一个函数<algorithm>
,并且它被模板化以用于任何类型。)
Another use is to remove that copy that happens when you call a function. Consider we have a data type that's very big. Copying this object takes a lot of time, and we'd like to avoid that:
另一个用途是删除调用函数时发生的副本。考虑我们有一个非常大的数据类型。复制这个对象需要很多时间,我们想避免这种情况:
struct big_data
{ char data[9999999]; }; // big!
void do_something(big_data data);
big_data d;
do_something(d); // ouch, making a copy of all that data :<
However, all we really need is an alias to the variable, so let's indicate that. (Again, back in C we'd pass the address of our big data type, solving the copying problem but introducing clumsiness.):
然而,我们真正需要的只是变量的别名,所以让我们指出这一点。(同样,回到 C 中,我们将传递我们的大数据类型的地址,解决了复制问题,但引入了笨拙。):
void do_something(big_data& data);
big_data d;
do_something(d); // no copies at all! data aliases d within the function
This is why you'll hear it said you should pass things by reference all the time, unless they are primitive types. (Because internally passing an alias is probably done with a pointer, like in C. For small objects it's just faster to make the copy then worry about pointers.)
这就是为什么你会听到它说你应该一直通过引用传递事物,除非它们是原始类型。(因为内部传递别名可能是用指针完成的,就像在 C 中一样。对于小对象,制作副本然后担心指针会更快。)
Keep in mind you should be const-correct. This means if your function doesn't modify the parameter, mark it as const
. If do_something
above only looked at but didn't change data
, we'd mark it as const
:
请记住,您应该是常量正确的。这意味着如果您的函数不修改参数,请将其标记为const
. 如果do_something
上面只看但没有改变data
,我们将其标记为const
:
void do_something(const big_data& data); // alias a big_data, and don't change it
We avoid the copy andwe say "hey, we won't be modifying this." This has other side effects (with things like temporary variables), but you shouldn't worry about that now.
我们避免复制并说“嘿,我们不会修改它。” 这还有其他副作用(例如临时变量),但您现在不必担心。
In contrast, our swap
function cannot be const
, because we are indeed modifying the aliases.
相反,我们的swap
函数不能是const
,因为我们确实在修改别名。
Hope this clarifies some more.
希望这能澄清更多。
*Rough pointers tutorial:
*粗略的指针教程:
A pointer is a variable that holds the address of another variable. For example:
指针是保存另一个变量地址的变量。例如:
int i; // normal int
int* p; // points to an integer (is not an integer!)
p = &i; // &i means "address of i". p is pointing to i
*p = 2; // *p means "dereference p". that is, this goes to the int
// pointed to by p (i), and sets it to 2.
So, if you've seen the pointer-version swap function, we pass the address of the variables we want to swap, and then we do the swap, dereferencing to get and set values.
所以,如果你看过指针版本交换函数,我们传递我们想要交换的变量的地址,然后我们进行交换,取消引用以获取和设置值。
回答by outis
GMan's answer gives you the lowdown on references. I just wanted to show you a very basic function that must use references: swap
, which swaps two variables. Here it is for int
s (as you requested):
GMan 的回答为您提供了参考资料的内幕。我只是想向您展示一个非常基本的函数,它必须使用 references: swap
,它交换两个变量。这是用于int
s(根据您的要求):
// changes to a & b hold when the function exits
void swap(int& a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
// changes to a & b are local to swap_noref and will go away when the function exits
void swap_noref(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
// changes swap_ptr makes to the variables pointed to by pa & pb
// are visible outside swap_ptr, but changes to pa and pb won't be visible
void swap_ptr(int *pa, int *pb) {
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
int main() {
int x = 17;
int y = 42;
// next line will print "x: 17; y: 42"
std::cout << "x: " << x << "; y: " << y << std::endl
// swap can alter x & y
swap(x,y);
// next line will print "x: 42; y: 17"
std::cout << "x: " << x << "; y: " << y << std::endl
// swap_noref can't alter x or y
swap_noref(x,y);
// next line will print "x: 42; y: 17"
std::cout << "x: " << x << "; y: " << y << std::endl
// swap_ptr can alter x & y
swap_ptr(&x,&y);
// next line will print "x: 17; y: 42"
std::cout << "x: " << x << "; y: " << y << std::endl
}
There is a cleverer swap implementation for int
s that doesn't need a temporary. However, here I care more about clear than clever.
int
s有一个更聪明的交换实现,不需要临时。然而,在这里我更关心清晰而不是聪明。
Without references (or pointers), swap_noref
cannot alter the variables passed to it, which means it simply cannot work. swap_ptr
can alter variables, but it uses pointers, which are messy (when references won't quite cut it, however, pointers can do the job). swap
is the simplest overall.
没有引用(或指针),swap_noref
不能改变传递给它的变量,这意味着它根本无法工作。swap_ptr
可以改变变量,但它使用指针,这是凌乱的(当引用不会完全削减它时,指针可以完成这项工作)。swap
是最简单的整体。
On Pointers
关于指针
Pointers let you do some of the same things as references. However, pointers put more responsibility on the programmer to manage them and the memory they point to (a topic called "memory management"–but don't worry about it for now). As a consequence, references should be your preferred tool for now.
指针可以让你做一些与引用相同的事情。然而,指针让程序员承担更多的责任来管理它们和它们指向的内存(一个叫做“内存管理”的主题——但现在不要担心)。因此,参考现在应该是您的首选工具。
Think of variables as names bound to boxes that store a value. Constants are names bound directly to values. Both map names to values, but the value of constants can't be changed. While the value held in a box can change, the binding of name to box can't, which is why a reference cannot be changed to refer to a different variable.
将变量视为绑定到存储值的框的名称。常量是直接绑定到值的名称。两者都将名称映射到值,但不能更改常量的值。虽然保存在框中的值可以更改,但名称到框的绑定不能,这就是不能将引用更改为引用不同变量的原因。
Two basic operations on variables are getting the current value (done simply by using the variable's name) and assigning a new value (the assignment operator, '='). Values are stored in memory (the box holding a value is simply a contiguous region of memory). For example,
变量的两个基本操作是获取当前值(只需使用变量的名称即可完成)和分配新值(赋值运算符“=”)。值存储在内存中(保存值的框只是内存的一个连续区域)。例如,
int a = 17;
results in something like (note: in the following, "foo @ 0xDEADBEEF" stands for a variable with name "foo" stored at address "0xDEADBEEF". Memory addresses have been made up):
结果类似于(注意:在下面,“foo @ 0xDEADBEEF”代表一个名称为“foo”的变量存储在地址“0xDEADBEEF”。内存地址已经组成):
____
a @ 0x1000: | 17 |
----
Everything stored in memory has a starting address, so there's one more operation: get the address of the value ("&" is the address-of operator). A pointer is a variable that stores an address.
存储在内存中的所有内容都有一个起始地址,因此还有一个操作:获取值的地址(“&”是操作符的地址)。指针是存储地址的变量。
int *pa = &a;
results in:
结果是:
______ ____
pa @ 0x10A0: |0x1000| ------> @ 0x1000: | 17 |
------ ----
Note that a pointer simply stores a memory address, so it doesn't have access to the name of what it points to. In fact, pointers can point to things without names, but that's a topic for another day.
请注意,指针仅存储内存地址,因此它无法访问其指向的名称。事实上,指针可以指向没有名字的东西,但那是另一天的话题。
There are a few operations on pointers. You can dereference a pointer (the "*" operator), which gives you the data the pointer points to. Dereferencing is the opposite of getting the address: *&a
is the same box as a
, &*pa
is the same value as pa
, and *pa
is the same box as a
. In particular, pa
in the example holds 0x1000; * pa
means "the int in memory at location pa", or "the int in memory at location 0x1000". "a" is also "the int at memory location 0x1000". Other operation on pointers are addition and subtraction, but that's also a topic for another day.
有一些对指针的操作。您可以取消引用指针(“*”运算符),它为您提供指针指向的数据。取消引用与获取地址相反:*&a
与 相同的框a
,&*pa
与 相同的值pa
,以及*pa
与 相同的框a
。特别是,pa
在示例中持有 0x1000;* pa
表示“位于 pa 位置的内存中的 int”,或“位于 0x1000 位置的内存中的 int”。“a”也是“内存位置 0x1000 处的 int”。指针上的其他操作是加法和减法,但这也是另一天的话题。
回答by codaddict
Lets take a simple example of a function named increment
which increments its argument. Consider:
让我们举一个简单的例子,一个名为的函数increment
增加它的参数。考虑:
void increment(int input) {
input++;
}
which will not work as the change takes place on the copy of the argument passed to the function on the actual parameter. So
这将不起作用,因为更改发生在传递给实际参数上的函数的参数副本上。所以
int i = 1;
std::cout<<i<<" ";
increment(i);
std::cout<<i<<" ";
will produce 1 1
as output.
将产生1 1
作为输出。
To make the function work on the actual parameter passed we pass its reference
to the function as:
为了使函数在传递的实际参数上工作,我们将其传递reference
给函数,如下所示:
void increment(int &input) { // note the &
input++;
}
the change made to input
inside the function is actually being made to the actual parameter. This will produce the expected output of 1 2
对input
函数内部所做的更改实际上是对实际参数进行的。这将产生预期的输出1 2
回答by Stephen
// Passes in mutable references of a and b.
int doSomething(int& a, int& b) {
a = 5;
cout << "1: " << a << b; // prints 1: 5,6
}
a = 0;
b = 6;
doSomething(a, b);
cout << "2: " << a << ", " << b; // prints 2: 5,6
Alternatively,
或者,
// Passes in copied values of a and b.
int doSomething(int a, int b) {
a = 5;
cout << "1: " << a << b; // prints 1: 5,6
}
a = 0;
b = 6;
doSomething(a, b);
cout << "2: " << a << ", " << b; // prints 2: 0,6
Or the const version:
或 const 版本:
// Passes in const references a and b.
int doSomething(const int &a, const int &b) {
a = 5; // COMPILE ERROR, cannot assign to const reference.
cout << "1: " << b; // prints 1: 6
}
a = 0;
b = 6;
doSomething(a, b);
References are used to pass locations of variables, so they don't need to be copied on the stack to the new function.
引用用于传递变量的位置,因此它们不需要在堆栈上复制到新函数。
回答by Cam
A simple pair of examples which you can run online.
您可以在线运行的一对简单示例。
The first uses a normal function, and the second uses references:
第一个使用普通函数,第二个使用引用:
Edit - here's the source code incase you don't like links:
编辑 - 这是源代码,以防您不喜欢链接:
Example 1
示例 1
using namespace std;
void foo(int y){
y=2;
}
int main(){
int x=1;
foo(x);
cout<<x;//outputs 1
}
Example 2
示例 2
using namespace std;
void foo(int & y){
y=2;
}
int main(){
int x=1;
foo(x);
cout<<x;//outputs 2
}
回答by George R
How about by metaphor: Say your function counts beans in a jar. It needs the jar of beans and you need to know the result which can't be the return value (for any number of reasons). You could send it the jar and the variable value, but you'll never know if or what it changes the value to. Instead, you need to send it that variable via a return addressed envelope, so it can put the value in that and know it's written the result to the value at said address.
用比喻来说怎么样:假设你的函数计算罐子里的豆子。它需要豆子罐,您需要知道不能作为返回值的结果(出于多种原因)。您可以将 jar 和变量值发送给它,但您永远不会知道它是否或将值更改为什么。相反,您需要通过返回地址信封向它发送该变量,以便它可以将值放入其中并知道它已将结果写入所述地址处的值。
回答by Biber
Correct me if I'm wrong, but a reference is only a dereferenced pointer, or?
如果我错了,请纠正我,但引用只是一个取消引用的指针,或者?
The difference to a pointer is, that you can't easily commit a NULL.
与指针的不同之处在于,您不能轻易提交 NULL。
回答by Mike DeSimone
I don't know if this is the most basic, but here goes...
我不知道这是否是最基本的,但这里是......
typedef int Element;
typedef std::list<Element> ElementList;
// Defined elsewhere.
bool CanReadElement(void);
Element ReadSingleElement(void);
int ReadElementsIntoList(int count, ElementList& elems)
{
int elemsRead = 0;
while(elemsRead < count && CanReadElement())
elems.push_back(ReadSingleElement());
return count;
}
Here we use a reference to pass our list of elements into ReadElementsIntoList()
. This way, the function loads the elements right into the list. If we didn't use a reference, then elems
would be a copyof the passed-in list, which would have the elements added to it, but then elems
would be discarded when the function returns.
这里我们使用一个引用将我们的元素列表传递到ReadElementsIntoList()
. 这样,该函数将元素直接加载到列表中。如果我们不使用引用,那么elems
将是传入列表的副本,其中将添加元素,但elems
在函数返回时将被丢弃。
This works both ways. In the case of count
, we don'tmake it a reference, because we don't want to modify the count passed in, instead returning the number of elements read. This allows the calling code to compare the number of elements actually read to the requested number; if they don't match, then CanReadElement()
must have returned false
, and immediately trying to read some more would likely fail. If they match, then maybe count
was less than the number of elements available, and a further read would be appropriate. Finally, if ReadElementsIntoList()
needed to modify count
internally, it could do so without mucking up the caller.
这是双向的。在 的情况下count
,我们不让它成为引用,因为我们不想修改传入的计数,而是返回读取的元素数。这允许调用代码将实际读取的元素数量与请求的数量进行比较;如果它们不匹配,则CanReadElement()
必须返回false
,并且立即尝试阅读更多内容可能会失败。如果它们匹配,那么可能count
少于可用元素的数量,进一步阅读将是合适的。最后,如果ReadElementsIntoList()
需要在count
内部修改,它可以在不破坏调用者的情况下进行。