Possible Duplicate:
Function argument type followed by *&
I am looking at someone else's code right now and saw an unusual (atleast for me) function declaration syntax. Is the following valid C++ syntax?
bool Foo::Bar(Frame *&ptoframe, int msToBlock)
{
....
}
I think the developer is trying to declare a pointer to a reference.
thanks for the help
Yes, it's valid. Read the syntax from right to left: it's read reference to a pointer. This is important if you wish to change the pointer being passed to the function. The pointer is effectively passed by reference just like any other parameter.
Here's a pretty example:
void no_change(int * ptr) {
ptr = 0;
}
void change_ptr(int *& ptr) {
ptr = 0;
}
int main() {
int *x;
change_ptr(x);
}
The value of any pointer passed to change_ptr
will be changed because we are passing it by reference.
Note, however that the value of the object to which a pointer points can still be changed through the no_change
function (i.e *ptr = new int
). This syntax is applying only to the actual pointer, not its pointed-to object.
No, the first function parameter is a reference to a pointer. Sometimes you want to change someone else's pointer... To wit:
void change_my_char(char & c) { c = 'x'; }
void pimp_my_pointer(void * & p) { p = nullptr; }
int main() {
char x;
void * y;
change_my_char(x);
pimp_my_pointer(y);
}
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