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.
user3995702
source share