采用以下代码,其中函数通过引用返回:
#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;
}
除了返回对函数局部变量的引用的明显陷阱(这里不是这种情况)之外,在这种设置中还有什么需要注意的地方吗?换句话说,除了通过引用简单地返回事物以避免不必要的复制操作的函数之外,这段代码还有什么“更多”吗?
最佳答案
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();
关于C++通过引用返回有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104398/