Const refers to a pointer that does not behave as expected

Why am I getting an error message at startup? I expected ptr_ref to not be able to change the address pointed to by ptr, but things don't seem to be planned.

int b = 3; int* ptr = &b; //says something about cannot convert int* to type const int*& const int*& ptr_ref = ptr; 

Thanks in advance, 15 years C ++ noob

+6
source share
3 answers

ptr_ref not declared as a const reference to a pointer to an int , but rather a reference to a pointer to a const int , so you have a type mismatch. You will need to do

 int* const& ptr_ref = ptr; 
+10
source

The problem is that the types do not match, and therefore you cannot create a link.

 int b = 3; int* ptr = &b; int*& ptr_ref = ptr; 

It is legal.

 int b = 3; const int* ptr = &b; const int*& ptr_ref = ptr; 

It is legal.

 int b = 3; int* ptr = &b; const int*& ptr_ref = ptr; 

It is a mismatch.

The g ++ error message may be useful to you:

 error: invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*' const int*& ptr_ref = ptr; ^ 

In essence, for this expression he needed to create a const int* , which is an rvalue (essentially a temporary object) and so you cannot refer to it. Simply put, you cannot do what you wrote for the same reason that it is illegal:

 int& added = 3 + 2; 

Depending on your situation, you can solve this by simply deleting the reference symbol. Most compilers will output an identical assembly with or without it, at least when it is optimized, because of their ability to understand that your variable name is just an alias.

There are even some cases of links that can get worse , which, depending on your intentions, can be useful - I was surprised to find out when I found out.

+3
source

The link is essentially const, so it makes no sense to define it as int *& const ptr_ref = ptr When you talk about a constant link, it usually means a reference to a constant, which is the definition you used in your question.

[edit] Edited my answer, because I put const by mistake on the wrong side of the ampersand - C ++ will not forgive you [/ edit]

-3
source

All Articles