Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to a reference parameter [duplicate]

Tags:

c++

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

like image 645
user947158 Avatar asked Dec 11 '22 19:12

user947158


2 Answers

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.

like image 193
David G Avatar answered Dec 14 '22 08:12

David G


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);
}
like image 42
Kerrek SB Avatar answered Dec 14 '22 09:12

Kerrek SB