return by reference : what's different here ??

Hi guys,

i've two functions declared like the following.

1
2
3
4
5
6
7
int& readRef(int& num){
return num;
}

int readNormal(int& num){
return num;
}

I thought the function readRef() returns a reference to num, so i can change the value of through that reference. But, it's not happening. Effectively, there's no difference between these two functions, then. But, it can't be. I would be very thankful to the guy(s) who explain where i was wrong.
Last edited on
The first version returns a reference to num. num stops to exist when the function ends so the caller never gets a chance to read the value of num. It might look like it works but it is undefined behaviour so anything is allowed to happen.

The second version returns a copy of num so this is safe.
readRef() returns a dangling reference, that is, a reference to an object that no longer exists. It is an error to do so.

readNormal() is, well, normal.

An example of a function that meaningfully returns a reference would be operator[] in a container:
1
2
3
4
5
class Container {
    vector<int> data;
 public:
    int& operator[](size_t idx) { return data.at(idx); }
};

Here the reference returned by calling the function remains valid because the object it's pointing to (some element of data) remains in existence after the function returns.
Last edited on
@peter87, @Cubbi : thanks for your kind replies. Actually, there was a typing mistake in my post. Can you guys help me what'll happen now.
Why... this, then?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int & crazy(int &i)
{
    return i;
}

int main()
{
    int i=43;

    crazy(i) += 57;
    std::cout << i << std::endl;
}
100


Edit: I apologize for my hasty comment. I now realize that sathya691 edited the original post after Cubbi replied.

Well sathya, when you do not use references, the variables you return or parameters you input are copies. Which is why, if you forget the & in int &num, you'll have a dangling reference as soon as the function ends.

In your current code, things should be fine.
Last edited on
Topic archived. No new replies allowed.