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) 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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With