Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a const pointer reference to a non-const pointer

int val2 = 38;
int *ptr = &val2;
const int *&ptrRef = ptr; // ERROR

int i = 92;
int &ref_i = i;
const int &ref_i2 = ref_i;  // OK

Why I can't have a const reference that references to a non-const pointer? I thought that if you access the const ptrRef identifier, it will treat val2 as const. When you access ptr, it will treat val2 as non-const. This works for the bottom part of the code, so I don't understand why it won't work for pointers.

like image 935
Goddrew Avatar asked Jul 22 '26 04:07

Goddrew


1 Answers

East-const makes it clearer:

int const * & ptrRef = ptr; // ERROR

It's the pointer that is const. However, ptr is a different type. You can't bind a reference to a different type. It requires a conversion, making the initializer a temporary (ptr converted to int const*).

Now, there's a more confusing catch: const references can bind to temporaries, extending their lifetime: Why do const references extend the lifetime of rvalues?

They e.g. allow funtions to take arguments by const& and still be callable with temporaries:

void foo(std::string const&);

foo("foor"s+"bar"s); // still ok
like image 145
sehe Avatar answered Jul 24 '26 17:07

sehe