In the C++ primer, I found that const int &
can bind with a int object.I don't understand that,because I think const int &
should bind with a const int
not a int
object, the int
object can change, the book explain this question for that when the const int &
object bind with int
; there is a temporary object between the two, for example:
int a=0;
const int &r=a;
We can use b
as the temporary value, so above is equal that:
const int b=a;
const int &r=b;
But I think the book is not right, because if there is a temporary like b
existing between a
and r
,the value of r
can't be changed, but when I debug the following coding in visual studio, I found it is not right:
int a=0;
const int &r=a;
a=3;
cout<<r<<endl;
The output is that r=3;
the value of r
can be changed, why? I don't understand that.
The first const keyword can go either side of data type, hence int const* is equivalent to const int*.
const int* const says that the pointer can point to a constant int and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant int. Thumb rule is to naming syntax from right to left.
The constant variable values cannot be changed after its initialization.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
don't understand that,because I think
const int &
should bind with aconst int
not aint
object
You are mistaken. A reference-to-const (const reference in short) doesn't mean that only const objects can be bound. It means that the object can not be modified through the reference.
What is not allowed would be to bind a non-const reference to a const object, because such reference could be used to modify the object which would break the constness.
the value of
r
can be changed, why?
The object that r
refers to was modified - which is OK because the object isn't const. r
still refers to the same object and the object was not modified using r
.
Having a const reference does not mean that the referred object can not change. It means that the object can not be changed using that reference.
If you wish to have an object that can not change, then that object itself has to be const. A const reference does not make the referred object const. The book has shown you how to create a const object:
const int b=a;
I have regarded reference as poiter mistakely,because they are similiar some time.
Indeed, references are very similar to pointers. Regarding the context of this question, they behave similarly. A demo:
int a=0;
const int *r=&a;
a=3;
cout<<*r<<endl;
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