C++ – Non-Const Reference to Non-Const Pointer to Const Object

c++pointersreference

In simple words I have a simple pointer:

int* a;

now, I would like to change value of this pointer. I want to do this in a function. Function assures, that it will not change object, that pointer points to, but will change a pointer itself. This is why I would like this function to take argument like: non-const reference (because value of pointer will be changed) to the non-const pointer(pointer itself can be changed) pointing to const object (function assures, that object, that pointer points to will not be changed).

The simplest function would be:

void function(const int*& a){
    a = 0;
}

but when I try to call this function:

int main(){
    int* a;
    function(a);
    return 0;
}

Compiler is unhappy and says:

invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*'
function(a);

I cannot quite understand this error, as for me there is no rvalue involved (I am passing a reference to object, that already exists on the stack.)

Question is, how can I do it properly?

Example can be found here: https://ideone.com/D45Cid


EDIT:

It was suggested, that my question is simillar to the Why isn't it legal to convert "pointer to pointer to non-const" to a "pointer to pointer to const"

My question is different as I do not use pointer to pointer I use only pointer to object/value and store reference to it, therefore situation like in the answer to that question:

const char c = 'c';
char* pc;
const char** pcc = &pc;   // not allowed
*pcc = &c;
*pc = 'C';                // would allow to modify a const object

Is impossible in my case, as I cannot dereference the top level pointer (I do not have such a pointer).

Moreover I questioned about nice and clean solution to this problem, which is not covered in a question

Best Answer

I cannot quite understand this error, as for me there is no rvalue involved (I am passing a reference to object, that already exists on the stack.)

int* and const int* are different things. When you pass a of type int* to function(const int*&), it need to be implicitly casted to const int* firstly, which is temporary, i.e. rvalue, and couldn't be bound to non-const referece. That's why compiler complains.

Question is, how can I do it properly?

You could change the type of a or the parameter type of function() to make them match exactly (might be const int* if you won't change the value pointed by the pointer), to avoid the implicit conversion and temporary variable. Or as @TartanLlama suggested, return the new value of pointer from function().