In the "C++ programming language", there is an example
void g()
{
int ii = 0;
int& rr = ii;
rr++;
int* pp = &rr;
}
The author states:
This is legal, but rr++ does not increment the reference rr, rather, ++ is applied to an int that happens to be ii.
I am quite confusing about this statement, why "rr++ does not increment the reference rr"? So rr is just used as "bridge" to increment ii?
Yes, in C++ a reference is nothing more than an alias, or a "bridge" as you say. Any time you say rr, it is as if you'd said ii, the "original" name of the variable that rr references.
That is different from references in many other languages (which behave more like C++'s pointers). In C++, references are not objects, they have no separate identity. You can't tell the reference to "please increment", or "please point to null" or anything else. It just becomes another name for the variable that the reference points to.
A reference is similar to a dereferenced pointer to a variable. For example:
int v = 3;
int* pv = &v;
int& rv = v;
// Access v through a pointer:
*pv = 4;
// Access v through a reference:
rv = 4;
In this example, both statements will set v to 4.
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