Argument passing by reference to pointer problem
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.