Quick Q: What does it mean to return a reference?

Quick A: The returned variable can be modified.

Recently on SO:

What does it mean to return a reference?

It means you return by reference, which is, at least in this case, probably not desired. It basically means the returned value is an alias to whatever you returned from the function. Unless it's a persistent object it's illegal.

For example:

int& foo () {
    static int x = 0;
    return x;
}

//...
int main()
{
    foo() = 2;
    cout << foo();
}

would be legal and print out 2, because foo() = 2 modifies the actual value returned by foo.

However:

int& doit () {
    int x = 0;
    return x;
}

would be illegal (well, accessing the returned value would), because x is destroyed when the method exits, so you'd be left with a dangling reference.

Returning by reference isn't common for free functions, but it is for methods returning members. For example, in the std, the operator [] for common containers return by reference. For example, accessing a vector's elements with [i] returns an actual reference to that element, so v[i] = x actually changes that element.

Also, I hope that "is essentially equal to this code" means that they're semantically sort of (but not really) similar. Nothing more.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.