space_voyager
space_voyager

Reputation: 2034

C++ return by reference what are the effects?

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?

Upvotes: 0

Views: 181

Answers (2)

The Quantum Physicist
The Quantum Physicist

Reputation: 26286

The code you provided works because you're passing the variable to your function by reference, and still returning it by reference. This is consistent and works, but is weird. Why would you return the same variable that you're passing by reference? (I just remembered from the comments that this is useful for chaining in std::ostream, for example.)

On the other hand, if you pass that variable by value, you'll have a dangling reference and it won't work. So this won't work:

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

In my opinion, the only return by reference I find appropriate is if you return a variable from inside a class's method. Besides that, I don't think you should return by reference at all.

You can catch a variable as a constant reference and avoid copying it if you want without having a dangling if you do this:

int myFunction(int input) {
    return input;
}

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

This is a special case that.

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36483

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?

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?

There's still a copy being made here:

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.

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();

Upvotes: 1

Related Questions