返回引用是什么意思? [英] What does it mean to return a reference?

查看:130
本文介绍了返回引用是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解C ++中引用的概念,也了解它们在函数参数中使用时的作用,但是我仍然对它们如何与返回类型一起使用感到非常困惑.

I understand the concept of references in C++, and I understand what they do when used in function parameters, but I am still very much confused on how they work with return types.

例如,在参数中使用时,此代码:

For example, when used in parameters, this code:

int main (void) {
  int foo = 42;
  doit(foo);
}

void doit (int& value) {
  value = 24;
}

类似于以下代码:

int main (void) {
  int foo = 42;
  doit(&foo);
}

void doit (int* value) {
  *value = 24;
}

(知道编译器每次在 doit 的第一个代码示例中使用它时,都会在 value 前面自动添加一个星号,但是在后者中,您d每次尝试使用 value )

(knowing that the compiler will automatically put an asterisk in front of value every time it is used in the first code sample of doit, but in the latter you'd have to put the asterisk in yourself every time you try to use value)

那么当用作参考时,下一个代码(在返回类型中使用参考)将转换为什么?它是否返回一个指向int的指针?还是会返回整数?

So when used as a reference what does this next code (using reference in a return type) translate to? Does it return a pointer to an int? Or would it just return an int?

int main (void) {
  int* foo = /*insert useful place in memory*/;
  foo = doit(foo);
}

int& doit (int* value) {
  //insert useful code
}

推荐答案

这意味着您通过引用返回,至少在这种情况下,可能不希望这样做.基本上,这意味着返回的值是您从函数返回的任何内容的别名.除非它是一个持久对象,否则它是非法的.

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.

例如:

int& foo () {
    static int x = 0;
    return x;
}

//...
int main()
{
    foo() = 2;
    cout << foo();
}

是合法的并打印出2,因为foo() = 2修改了foo返回的实际值.

would be legal and print out 2, because foo() = 2 modifies the actual value returned by foo.

但是:

int& doit () {
    int x = 0;
    return x;
}

将是非法的(嗯,访问返回的值将是非法的),因为x在该方法退出时会被破坏,因此您将留下一个悬挂的引用.

would be illegal (well, accessing the returned value would), because x is destroyed when the method exits, so you'd be left with a dangling reference.

对于自由函数,通过引用返回并不常见,但是对于返回成员的方法而言,返回引用并不常见.例如,在std中,常见容器的operator []通过引用返回.例如,使用[i]访问向量的元素会返回对该元素的实际引用,因此v[i] = x实际上会更改该元素.

Returning by reference isn't common for free functions, but it is for methods returning members. For example, in the std, the operator [] for common containers return by reference. For example, accessing a vector's elements with [i] returns an actual reference to that element, so v[i] = x actually changes that element.

此外,我希望基本上等于此代码"意味着它们在语义上有点类似(但不是真的).没什么.

Also, I hope that "is essentially equal to this code" means that they're semantically sort of (but not really) similar. Nothing more.

这篇关于返回引用是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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