Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to reference

Tags:

c++

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?

like image 204
MEMS Avatar asked Jun 09 '16 09:06

MEMS


People also ask

Can you make a pointer to a reference?

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.

Can you make a pointer to a reference C++?

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 .

Can you emulate a reference with a pointer?

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.

Is pointer same as reference?

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.


2 Answers

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.

like image 57
Vittorio Romeo Avatar answered Sep 24 '22 06:09

Vittorio Romeo


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.

like image 21
Marcus Müller Avatar answered Sep 25 '22 06:09

Marcus Müller