Reputation: 327
Is it ok to create references for reference variables (alias for an alias in itself ) ?
If yes, what is its application ?
Upvotes: 0
Views: 284
Reputation: 1
In Python, like this:
a = 1
b = a
after this processing, the id for "a" and "b" is the same one.
Upvotes: 0
Reputation: 477030
In C++98, it was illegal to form references to reference types. In C++11, there are new reference collapsing rules, which means in a nutshell that a reference to a reference is still just a reference (but there are subtleties regarding lvalue and rvalue references). Consider this code:
typedef int & ir;
int a;
ir & b = a;
In C++98, the last line is illegal, since ir &
is not a valid type (an attempted reference to a reference). In C++11, the references collapse and ir &
is the same as int &
.
Bear in mind that references are immutable, and once initialized you can never change the target of the reference. In the above code, b
will always be an alias of a
, and can never be changed into an alias to something else. Thus there is no need for a double indirection, as it wouldn't allow you to do anything more than what you already can do with ordinary references.
For completeness, the reference collapsing rules are as follows. Suppose T
is not a reference type. Then conceptually we have:
(T&)& == T& (T&)&& == T& (T&&)& == T& (T&&)&& == T&&
Upvotes: 4
Reputation: 279255
You can't create a reference to a reference, and C++ has no reference-to-reference types.
If you use a reference to initialize another reference, for example:
int i = 1;
int &a = i;
int &b = a;
Then what you've actually done is bound the referand of a
to b
. a
is a name for the same object that i
is a name for, and consequently int &b = a;
has exactly the same effect as int &b = i;
. So you have two references to the same object, i
.
I can't immediately think of a reason to have two references in the same function, but you'd commonly create multiple references if you have a function f
that takes a reference parameter, and passes this on to another function g
that also takes a reference parameter. Then f
and g
each has a reference to the same object.
Upvotes: 2