When one aliases two variables as
int a;
const int &b = a;
the two variables are effectively the same thing, so that any change applied to the variable a
is also applied to the variable b
. However, when the same trick is done with pointers, it does not seem to work in the same way, as is demonstrated by the following program:
#include <iostream>
int main(void) {
int *a = (int*) 0x1;
const int *const &b = a;// Now b should be an alias to a.
a = (int*) 0x2;// This should change b to 0x2.
std::cout << b << "\n";// Outputs 0x1 instead of the expected value of 0x2.
return 0;
}
Now the variable a
does not seem to be an alias of the variable b
after all, but why?
Pointer. In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const int* and int const* says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed.
const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type.
int const * ptr is the same thing as const int * ptr which means it is a pointer to a constant integer. In this case, you can change which constant integer variable the pointer is pointing to, but you cannot change the value of that integer variable. An easy way to decipher such declarations is to read them backwards.
const * int ptr; It means that pointer is constant here, it can point to an integer and then it cant change its pointing location. Difference in ptr and *ptr is self-explanatory. Here the int value that pointed by ptr is const.
const int *const &
is a reference to const
pointer to const int
. (Try to read it from right to left.) Note that the pointer's type is const int *
, but not int *
(i.e. the type of a
). References can't be bound with different type directly. For const int *const &b = a;
a temporary* (with type const int *
, copied from a
) will be constructed and then bound to the reference; the temporary has nothing to do with a
, so any modification on b
won't effect a
.
Note the difference. In the 1st sample, const
is quafied on int
; in the 2nd sample, const
is qualified on not only the pointer itself, but also the pointee, which makes two pointers different types (int *
vs. const int *
). If you want to qualify const
on it (which seems unnecessary for your experiment) you should only qualify it on the pointer itself, i.e. int * const &
.
*The lifetime of the temporary is extended to the lifetime of reference b
.
const int * const & b
means reference to const pointer to const int. What you want is int * const & b
Use this handy tool to decipher complex declarations. https://cdecl.org/
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