C++通过引用返回有什么作用?

标签 c++ reference pass-by-reference return-by-reference

采用以下代码,其中函数通过引用返回:

#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/

相关文章:

java - 添加 ImageIcon 的路径 - Java

c - 应该通过引用调用的函数不起作用

python - 在函数中同时返回 bool 值和变量? Python

c++ - 定义自引用接口(interface)的正确方法是什么?

C++,错误 : "no operator " == "matches these operands ", ostream/istream

PHP 数组引用;将引用保存在数组中供以后使用

c# - 更改冲突的程序集引用

java - 仅将 ArrayList 作为值而不是引用传递

c++ - 优化非成本变量访问

java - 在 C++ 或 Java 中以响应模式使用 cmd