5
votes

I've recently come across *& as a parameter in a function.
From what I've understood, it is similar to **.

Why is it needed in a function that is altering the pointer? E.g. with the new keyword

Let's say I have a pointer int* a, why would I have to pass the parameter as a "pointer reference" if I wanted to do a = new int; inside that function?

1
int *& is to int* as int& is to int. There is nothing special about pointers, they just have a funny spelling. - molbdnilo
@molbdnilo haha, that actually made sense. Thank you - user644361

1 Answers

10
votes

If the function takes int* as its parameter, then the pointer is passed by value itself, that means any modification on the pointer itself (not the pointee) inside the function has nothing to do with the original pointer. e.g.

void foo(int* a) { a = new int; }

int* a = nullptr;
foo(a);
// a is still nullptr here

If you change the parameter type to int*& it'll be different.

void foo(int*& a) { a = new int; }

int* a = nullptr;
foo(a);
// a gets modified