Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to return a reference?

I understand the concept of references in C++, and I understand what they do when used in function parameters, but I am still very much confused on how they work with return types.

For example, when used in parameters, this code:

int main (void) {
  int foo = 42;
  doit(foo);
}

void doit (int& value) {
  value = 24;
}

is similar to this code:

int main (void) {
  int foo = 42;
  doit(&foo);
}

void doit (int* value) {
  *value = 24;
}

(knowing that the compiler will automatically put an asterisk in front of value every time it is used in the first code sample of doit, but in the latter you'd have to put the asterisk in yourself every time you try to use value)

So when used as a reference what does this next code (using reference in a return type) translate to? Does it return a pointer to an int? Or would it just return an int?

int main (void) {
  int* foo = /*insert useful place in memory*/;
  foo = doit(foo);
}

int& doit (int* value) {
  //insert useful code
}
like image 748
crodriguez Avatar asked Dec 05 '12 07:12

crodriguez


Video Answer


1 Answers

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.

like image 87
Luchian Grigore Avatar answered Sep 21 '22 13:09

Luchian Grigore