I was reading, and I saw the following code:
template <> inline bool is_empty(const char* const& x) { return x==0 || *x==0; }
What does const char* const& x
mean?
I tried the following code to understand it:
void f(const char* const& x) { // whatever } void main() { char a = 'z'; char &j = a; f(a);//error f(*a);//error f(&a);//fine f(j);//error f(&j);//fine f('z');//error }
It works only for f(&a)
and f(&j)
.
What does const char* const& x
actually mean?
No, you can't make a pointer to a reference. If you use the address-of operator & on it you get the address of the object you're referencing, not the reference itself.
Once a reference is established to a variable, you cannot change the reference to reference another variable. To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber .
You can basically think of pointers and references as the same thing. They both refer to addresses. So if you pass an address (either as pointer or as reference) to a function, and the content of the address changes, then the change is still there at the end of the function.
A reference, like a pointer, is an object that you can use to refer indirectly to another object. A reference declaration has essentially the same syntactic structure as a pointer declaration. The difference is that while a pointer declaration uses the * operator, a reference declaration uses the & operator.
cdecl is an useful online tool to help beginners get used to complicated declarations.
Inserting const char* const& i
returns:
declare i as reference to const pointer to const char
The meaning of the declaration should be obvious now.
Let's take this apart:
the trailing &
means this is a reference to whatever the type is.
const char
is the type that's being pointed to
* const
means the pointer is constant
So, this is a reference to a const pointer to a const char. You can't change the char
that it points to (unless you cast away the constness
), and you can't change the pointer (i.e. make it point to something else). The pointer is passed by reference, so that no copying occurs.
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