Every time I try to compile my code I get error:
cannot convert parameter 1 from 'int *' to 'int *&'
The test code looks like this:
void set (int *&val){
*val = 10;
}
int main(){
int myVal;
int *pMyVal = new int;
set(&myVal); // <- this causes trouble
set(pMyVal); // <- however, this doesn't
}
I'd like to call that function in a single shot without creating a pointer somewhere only to pass it. And as pointers don't have constructors, something like this can't be done: set(int*(&myVal));
Is there any other way to pass a pointer by reference without needing to create a temporary variable?
Edit: By the way I know why the code fails to compile (I'm just passing the address which is possibly int and not an actual pointer). The question is how else can it be done.
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
Use the *&var Notation to Pass a Pointer to Object by Reference. On the other hand, we can use the *&var notation to pass a pointer by reference to the function. A pointer is an object itself. It can be assigned or copied to pass a reference to a pointer as a function parameter.
When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.
A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
A reference to non-const cannot bind to an rvalue. The result of the &
operator is an rvalue. Take a look at the difference between lvalues and rvalues or read a good C++ book.
Also, in your context, you don't need to pass by reference. The following is OK as well:
void set (int *val){
*val = 10;
}
The reference would be needed if you were to do something like this;
void set (int*& val){
val = new int; //notice, you change the value of val, not *val
*val = 10;
}
&myval
is an rvalue (of type int*
), because it's a temporary. It's a pointer, but you cannot modify it, because it's just created on the fly. Your function set
however requires a non-const reference, so you cannot pass it a temporary.
By contrast, pMyVal
is a named variable, thus an lvalue, so it can be passed as a non-constant reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With