C++按引用返回有什么作用? [英] C++ return by reference what are the effects?

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

问题描述

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

Take the following code, where a function returns 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? In other words, is there anything "more" to this code than a function which simply returns things by reference in order to avoid unnecessary copying operations?

推荐答案

除了返回对本地的引用的明显陷阱函数的变量(这里不是这种情况),有没有在这种设置中需要注意什么?

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 的当前状态)

No, not really, it's perfectly valid but it has no advantage either. (in the current state of myFunction)

为了避免不必要的复制操作?

in order to avoid unnecessary copying operations?

这里还有一个副本:

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

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

This is less readable and doesn't speed up anything when it comes to just normal initialization:

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

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

There's no reason to do this in this situation, just stick to normal initialization.

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

Of course, if myFunction adds some kind of modification to a more complex object than int& then you can take advantage of returning the reference as you can then:

chain.method().calls();

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

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