Pass a reference to a reference

纵饮孤独 提交于 2020-01-01 09:35:12

问题


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 ??


回答1:


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;
}



回答2:


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.




回答3:


In the body of f, the value of the expression x is an int. The fact that the variable x has type int & means that the value of the expression is an lvalue, and thus it can bind to the parameter of the function g.




回答4:


A reference is an alias to a different object. Once the reference has been initialized, it behaves exactly as if you were accessing the object directly, so you are not passing a reference to a reference, but rather a reference to the real object (to which you refer by another reference).

Creating a reference to a reference would be something like:

typedef int& intr;
void f(intr& x);    // reference to a reference type



回答5:


Nowhere in your code you attempt to pass a reference to a reference. Inside f expression x produces an lvalue of type int. It is not a reference. Expressions in C++ never produce accessible results of reference type, since any results of reference type are immediately interpreted by the language as lvalues of non-reference type.

See 5/5

If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

P.S. I'm not sure what you mean by "Doesn't the formal parameter of g() qualify as a reference to a reference". The formal parameter of g is declared as int &. Where do you see "a reference to a reference" here?



来源:https://stackoverflow.com/questions/18473496/pass-a-reference-to-a-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!