I'd like to know what's the difference between const ref and const pointer in c++. When I declare on something to be const ref, can I change it's VALUE? or the const goes on the object? Because I know that const pointer means you cannot change the POINTER but you can change the VALUE it points to.
for example:
const char& a; // ?
const char* a; // pointer is const
Fred const& x;
It means x aliases a Fred object, but x can't be used to change that Fred object.
Fred const* p;
Fred const* p means "p points to a constant Fred": the Fred object can't be changed via p.
Fred* const p;
Fred* const p means "p is a const pointer to a Fred": you can't change the pointer p, but you can change the Fred object via p.
It's possible to combine the last to to get:
Fred const* const p;
Fred const* const p means "p is a constant pointer to a constant Fred": you can't change the pointer p itself, nor can you change the Fred object via p.
For more on this visit this link .
const char* a; // pointer is const
Wrong, this is a pointer to a constant. This:
char* const a; // pointer is const
is a constant pointer.
I prefer to write these like this: char const * a
vs. char * const a
.
This allows you to read from right to left: char const * a
is: a
is a pointer to a constant char
, and char * const a
is: a
is a constant pointer to a char
. And if I read other code, I just remember that const char* a = char const* a
.
To answer the other part of your question: When I declare on something to be const ref, can I change it's VALUE? People misuse the term const ref to actually mean reference to a constant (since a constant reference makes no sense). So, const ref const char& a
means that you cannot change the value. But if you actually mean you want a constant reference, char& const a
then you can change the value and the const
part makes no difference.
For pointers, const char* a
means you cannot change the value a
points to. Compare this to char* const a
which means you cannot change the pointer, but you can change the value a
points to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.