C++ return by reference有什么作用?

C++ return by reference what are the effects?

取如下代码,其中一个函数returns被引用:

#include <cstdio>
using namespace std;

int & myFunction(int & input) {
    return input;
}

int main() {
    int x;
    int y = 10;
    x = myFunction(y);
    printf("x is %d\n",x); // x is 10
    printf("y is %d\n",y); // y is 10
    x = 20;
    printf("x is %d\n",x); // x is 20
    printf("y is %d\n",y); // y is 10
    return 0;
}

除了返回对函数局部变量的引用的明显陷阱(这里不是这种情况)之外,在这种设置中还有什么需要注意的地方吗?换句话说,除了通过引用简单地 returns 以避免不必要的复制操作的函数之外,这段代码还有什么 "more" 吗?

您提供的代码有效,因为您通过引用将变量传递给您的函数,并且仍然通过引用 return 传递它。这是一致的并且有效,但是很奇怪。为什么要 return 与您通过引用传递的变量相同? (我只是从评论中记起这对于链接 std::ostream 很有用。)

另一方面,如果您按值传递该变量,您将有一个悬空引用,它不会起作用。所以这个行不通:

int & myFunction(int input) {
    return input;
}

在我看来,我认为唯一合适的 return 引用是 return 来自 class 方法内部的变量。除此之外,我认为您根本不应该 return 作为参考。

您可以 捕获 一个变量作为常量引用,如果您愿意,可以避免复制它而不会出现悬空,如果您这样做:

int myFunction(int input) {
    return input;
}

int main()
{
    const int& myInt = myFunction();
    //myInt is still valid here
}

这是一个特例。

Except the obvious pitfall of returning a reference to a local variable of the function (which is not the case here), are there any things to watch out for in this kind of setup?

不,不是真的,它完全有效,但也没有任何优势。 (目前状态myFunction

in order to avoid unnecessary copying operations?

这里还有一个正在复制:

int x;
int y = 10;
x = myFunction(y); // value of y is copied to x.

这可读性较差,并且在正常初始化时不会加快任何速度:

int x;
int y = 10;
x = y;

在这种情况下没有理由这样做,只需坚持正常初始化即可。

当然,如果 myFunction 对比 int& 更复杂的对象添加某种修改,那么您可以利用返回引用的优势:

chain.method().calls();