I'll try to explain, but someone else probably will be able to do a better job.
First, the
const int&
thing. Doing
const type& is special because it can extend the lifetime of a temporary created, to allow it to still be viewed as a reference to an object (but you can't change this object because it's const).
in my opinion * ptr is the value of a , that is a number, too |
The issue is the loose usage of the word "number" here. Yes,
*int_ptr (dereferenced int pointer) is a number, but the term "number" isn't very useful here.
I'm simplifying this a bit, but basically: there are
'rvalues' and
'lvalues'. An l-value is something that you can take the address of. Keep this in mind.
42 is an
int literal. You cannot take the address of 42. That is, you cannot do
int* ptr = &42;
. Therefore, 42 is not an lvalue. Likewise, you can't do
int& int_ref = 42;
. 42 will always be 42, and 42 doesn't have an address.
When you do
const int& int_ref = 42;
, internally the compiler does something like this:
1 2
|
int __special_internal_variable = 42; // copy the value 42 into the variable.
const int& int_ref = __special_internal_variable; // now, you can take a reference of an lvalue
| |
If this doesn't make sense to you, don't worry about it. Just note that const int& is special and allows you to still reference a temporary.
__________________________________
When you do
1 2
|
int a = 42;
int* ptr = &a;
| |
ptr is now the address of your a variable.
When you do (*ptr), you dereference your address, and you get a
reference to the value at that address.
This is what allows you to say
int& a_ref = *ptr;
Now,
a_ref is exactly the same object as
a.