I am passing in a reference to a pointer variable into a function. The function will do something and point the pointer variable to some object. Code:
int Foo(Obj* &ptr) {
// do something...
ptr = some_address;
return return_value;
}
int main() {
Obj* p = nullptr;
int ret = Foo(p);
// do something with ret
p->DoSomething();
}
However, things get trickier if I want to pass a reference to a pointer to const. I would like the pointer variable itself to be changed (hence the reference), but I don't want the pointed Obj
instance to change using this pointer. In my imagination, it should be something like:
int Foo(const Obj* &ptr) {
// do something...
ptr = some_address;
return return_value;
}
int main() {
const Obj* p = nullptr;
int ret = Foo(p);
// do something with ret
p->DoSomething(); // this should only work when DoSomething() is const method
}
EDIT: the following error cannot be reproduced and is hence deleted. This question is focused on the concept of reference-of-pointer instead of solving an issue
C++ gives this compile error:
main.cpp:22:10: error: cannot bind non-const lvalue reference of type ‘const Obj*&’ to an rvalue of type ‘const Obj*’ 22 | Foo(ptr); | ^~~ main.cpp:14:23: note: initializing argument 1 of ‘void test(const Obj*&)’ 14 | int Foo(const Obj* &ptr) { | ~~~~~~~~~~~~^~~
Some thoughts:
Error cannot be reproduced
- I believe this error is shown when I am trying to pass in an "unnamed variable" into a reference parameter. In this case I am passing the variable
ptr
, which shouldn't be an issue.
ptr
is passed in as a parameter because the function has a useful return value. Settingptr
is more like a side-product of this function, where the caller can choose to ignore or use.I can also try using
Obj**
as the parameter, which is passing by pointer instead of passing by reference. This works when aconst Obj**
is passed as parameter. I am just wondering what will be the case if the parameter is passed by reference.