Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a reference to a reference

I think it's illegal to pass a reference to a reference in C++.However ,when I run this code it gives me no error.

void g(int& y)
{
   std::cout << y;
   y++;
 }

 void f(int& x)
{
  g(x);
}
int  main()
{
  int a = 34;
  f(a);
  return 0;

 }

Doesn't the formal parameter of g() qualify as a reference to a reference ??

like image 928
devsaw Avatar asked Aug 27 '13 19:08

devsaw


2 Answers

1) There is nothing wrong with passing a reference to a reference (it is what the move-constructor and move-assignment operators use - though it is actually called a rvalue-reference).

2) What you are doing is not passing a reference to a reference, but rather passing the same reference through f to g:

void g(int& x)
{
    x = 5;
}

void f(int& x)
{
    std::cout << "f-in " << x << std::endl;
    g(x);
    std::cout << "f-out " << x << std::endl;
}

int main()
{
    int x = 42;
    f(x);
    std::cout << "New x = " << x << std::endl;
}
like image 157
Zac Howland Avatar answered Oct 28 '22 03:10

Zac Howland


No, g() is not taking a reference to reference. It takes a reference to an int. f() forwards the reference to int it receives to g().

A "reference to a reference" doesn't actually exist, but there are rvalue references, which are like references, but allow binding to temporaries.

like image 41
jxh Avatar answered Oct 28 '22 02:10

jxh