Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const reference to a pointer not behaving as expected

Why do I get an error when I run this? I was expecting ptr_ref to be unable to modify the address in which ptr is pointing to but things don't appear to be going as 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 yr old C++ noob

like image 307
Wasiim Ouro-sama Avatar asked May 20 '16 21:05

Wasiim Ouro-sama


People also ask

What does const do to a pointer?

Constant Pointers A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.

Is a reference a const pointer?

A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.

Can you have a const reference C++?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Can a const reference refer to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .


1 Answers

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

int* const& ptr_ref = ptr;
like image 88
Brian Bi Avatar answered Oct 14 '22 06:10

Brian Bi