返回参考是什么意思?

cro*_*uez 5 c++ parameters reference return-type

我理解C++中引用的概念,我理解它们在函数参数中使用时的作用,但我仍然对它们如何使用返回类型感到困惑.

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

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

void doit (int& value) {
  value = 24;
}
Run Code Online (Sandbox Code Playgroud)

类似于这段代码:

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

void doit (int* value) {
  *value = 24;
}
Run Code Online (Sandbox Code Playgroud)

(知道该编译器会自动把一个星号前面每次它的第一个代码示例中使用时间DOIT,但在后者,你也许就有您尝试使用的时候把星号在自己)

因此,当用作参考时,下一个代码(使用返回类型中的引用)转换为什么?它是否返回指向int的指针?或者只是返回一个int?

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

int& doit (int* value) {
  //insert useful code
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 14

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

例如:

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

//...
int main()
{
    foo() = 2;
    cout << foo();
}
Run Code Online (Sandbox Code Playgroud)

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

然而:

int& doit () {
    int x = 0;
    return x;
}
Run Code Online (Sandbox Code Playgroud)

将是非法的(好吧,访问返回的值),因为x当方法退出时被销毁,所以你将留下一个悬空引用.

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

此外,我希望"基本上等于这个代码"意味着它们在语义上类似(但不是真的)相似.而已.