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?
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
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