Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reference pointer as parameter to alter pointer

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?

like image 754
user644361 Avatar asked Jan 02 '23 05:01

user644361


1 Answers

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
like image 59
songyuanyao Avatar answered Jan 03 '23 17:01

songyuanyao